<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js">

<head>
    <!-- Book generated using mdBook -->
    <meta charset="UTF-8">
    <title>exercisms.io 快速练习</title>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta name="description" content="exercisms 的练习，网页版.">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#ffffff" />

    <link rel="shortcut icon" href="favicon.png">
    <link rel="stylesheet" href="css/variables.css">
    <link rel="stylesheet" href="css/general.css">
    <link rel="stylesheet" href="css/chrome.css">
    <link rel="stylesheet" href="css/print.css" media="print">

    <!-- Fonts -->
    <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800"
        rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">

    <!-- Highlight.js Stylesheets -->
    <link rel="stylesheet" href="highlight.css">
    <link rel="stylesheet" href="tomorrow-night.css">
    <link rel="stylesheet" href="ayu-highlight.css">

    <!-- Custom theme stylesheets -->
    
    <link rel="stylesheet" href="theme/custom.css">
    

    
</head>

<body class="light">
    <!-- Provide site root to javascript -->
    <script type="text/javascript">var path_to_root = "";</script>

    <!-- Work around some values being stored in localStorage wrapped in quotes -->
    <script type="text/javascript">
        try {
            var theme = localStorage.getItem('mdbook-theme');
            var sidebar = localStorage.getItem('mdbook-sidebar');

            if (theme.startsWith('"') && theme.endsWith('"')) {
                localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
            }

            if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
            }
        } catch (e) { }
    </script>

    <!-- Set the theme before any content is loaded, prevents flash -->
    <script type="text/javascript">
        var theme;
        try { theme = localStorage.getItem('mdbook-theme'); } catch (e) { }
        if (theme === null || theme === undefined) { theme = 'light'; }
        document.body.className = theme;
        document.querySelector('html').className = theme + ' js';
    </script>

    <!-- Hide / unhide sidebar before it is displayed -->
    <script type="text/javascript">
        var html = document.querySelector('html');
        var sidebar = 'hidden';
        if (document.body.clientWidth >= 1080) {
            try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch (e) { }
            sidebar = sidebar || 'visible';
        }
        html.classList.remove('sidebar-visible');
        html.classList.add("sidebar-" + sidebar);
    </script>

    <nav id="sidebar" class="sidebar" aria-label="Table of contents">
        <ol class="chapter"><li><a href="index.html"><strong aria-hidden="true">1.</strong> 超过 88 道练习，任点</a></li><li><a href="low.html"><strong aria-hidden="true">2.</strong> 易</a></li><li><ol class="section"><li><a href="hello-world/README.zh.html"><strong aria-hidden="true">2.1.</strong> hello world</a></li><li><a href="gigasecond/README.zh.html"><strong aria-hidden="true">2.2.</strong> 千兆秒 &gt;&lt; Gigasecond)</a></li><li><a href="leap/README.zh.html"><strong aria-hidden="true">2.3.</strong> 闰年 &gt;&lt; Leap</a></li><li><a href="raindrops/README.zh.html"><strong aria-hidden="true">2.4.</strong> 雨滴声 &gt;&lt; Raindrops</a></li><li><a href="reverse-string/README.zh.html"><strong aria-hidden="true">2.5.</strong> 反转字符串 &gt;&lt; Reverse String</a></li><li><a href="nth-prime/README.zh.html"><strong aria-hidden="true">2.6.</strong> 第 n 个素数 &gt;&lt; Nth Prime</a></li><li><a href="bob/README.zh.html"><strong aria-hidden="true">2.7.</strong> 迟钝孩子 &gt;&lt; Bob</a></li><li><a href="beer-song/README.zh.html"><strong aria-hidden="true">2.8.</strong> 啤酒之歌 &gt;&lt; Beer Song</a></li><li><a href="proverb/README.zh.html"><strong aria-hidden="true">2.9.</strong> 谚语串烧 &gt;&lt; Proverb</a></li><li><a href="difference-of-squares/README.zh.html"><strong aria-hidden="true">2.10.</strong> 平方差 &gt;&lt; Difference Of Squares</a></li><li><a href="sum-of-multiples/README.zh.html"><strong aria-hidden="true">2.11.</strong> 倍数之和 &gt;&lt; Sum Of Multiples</a></li><li><a href="grains/README.zh.html"><strong aria-hidden="true">2.12.</strong> 谷物 &gt;&lt; Grains</a></li><li><a href="pythagorean-triplet/README.zh.html"><strong aria-hidden="true">2.13.</strong> 勾股数 &gt;&lt; Pythagorean Triplet</a></li><li><a href="prime-factors/README.zh.html"><strong aria-hidden="true">2.14.</strong> 素数因子 &gt;&lt; Prime Factors</a></li><li><a href="series/README.zh.html"><strong aria-hidden="true">2.15.</strong> 子串 &gt;&lt; Series</a></li><li><a href="armstrong-numbers/README.zh.html"><strong aria-hidden="true">2.16.</strong> 水仙花数 &gt;&lt; Armstrong Numbers</a></li><li><a href="collatz-conjecture/README.zh.html"><strong aria-hidden="true">2.17.</strong> 3n+1 猜想 &gt;&lt; Collatz Conjecture</a></li><li><a href="diffie-hellman/README.zh.html"><strong aria-hidden="true">2.18.</strong> 迪菲-赫尔曼密钥交换 &gt;&lt; Diffie Hellman</a></li></ol></li><li><a href="medium.html"><strong aria-hidden="true">3.</strong> 中等</a></li><li><ol class="section"><li><a href="saddle-points/README.zh.html"><strong aria-hidden="true">3.1.</strong> 鞍点 &gt;&lt; Saddle Points</a></li><li><a href="isogram/README.zh.html"><strong aria-hidden="true">3.2.</strong> 等值线 &gt;&lt; Isogram</a></li><li><a href="say/README.zh.html"><strong aria-hidden="true">3.3.</strong> 英文说数字 &gt;&lt; Say</a></li><li><a href="run-length-encoding/README.zh.html"><strong aria-hidden="true">3.4.</strong> 游程编码 &gt;&lt; Run Length Encoding</a></li><li><a href="isbn-verifier/README.zh.html"><strong aria-hidden="true">3.5.</strong> 图书编号 &gt;&lt; ISBN Verifier</a></li><li><a href="perfect-numbers/README.zh.html"><strong aria-hidden="true">3.6.</strong> 数字也能分类 &gt;&lt; Perfect Numbers</a></li><li><a href="clock/README.zh.html"><strong aria-hidden="true">3.7.</strong> 时钟 &gt;&lt; Clock</a></li><li><a href="dot-dsl/README.zh.html"><strong aria-hidden="true">3.8.</strong> DOT DSL</a></li><li><a href="hamming/README.zh.html"><strong aria-hidden="true">3.9.</strong> 汉明距离 &gt;&lt; Hamming</a></li><li><a href="simple-linked-list/README.zh.html"><strong aria-hidden="true">3.10.</strong> 简单链表 &gt;&lt; Simple Linked List</a></li><li><a href="pascals-triangle/README.zh.html"><strong aria-hidden="true">3.11.</strong> 杨辉三角形 &gt;&lt; Pascal's Triangle</a></li><li><a href="scrabble-score/README.zh.html"><strong aria-hidden="true">3.12.</strong> 字母的分数游戏 &gt;&lt; Scrabble Score</a></li><li><a href="pangram/README.zh.html"><strong aria-hidden="true">3.13.</strong> 全字母句 &gt;&lt; Pangram</a></li><li><a href="paasio/README.zh.html"><strong aria-hidden="true">3.14.</strong> PaaS-IO-报告 &gt;&lt; Paasio</a></li><li><a href="nucleotide-count/README.zh.html"><strong aria-hidden="true">3.15.</strong> 核苷酸计数 &gt;&lt; Nucleotide Count</a></li><li><a href="luhn/README.zh.html"><strong aria-hidden="true">3.16.</strong> 模 10 算法 &gt;&lt; Luhn</a></li><li><a href="largest-series-product/README.zh.html"><strong aria-hidden="true">3.17.</strong> 最大数字子串乘积 &gt;&lt; Largest Series Product</a></li><li><a href="word-count/README.zh.html"><strong aria-hidden="true">3.18.</strong> 单词计数 &gt;&lt; Word Count</a></li><li><a href="atbash-cipher/README.zh.html"><strong aria-hidden="true">3.19.</strong> Atbash 加密 &gt;&lt; Atbash Cipher</a></li><li><a href="crypto-square/README.zh.html"><strong aria-hidden="true">3.20.</strong> 密码矩形 &gt;&lt; Crypto Square</a></li><li><a href="rotational-cipher/README.zh.html"><strong aria-hidden="true">3.21.</strong> 旋转密码 &gt;&lt; Rotational Cipher</a></li><li><a href="simple-cipher/README.zh.html"><strong aria-hidden="true">3.22.</strong> 简单加密 &gt;&lt; Simple Cipher</a></li><li><a href="rail-fence-cipher/README.zh.html"><strong aria-hidden="true">3.23.</strong> 栅栏密码 &gt;&lt; Rail Fence Cipher</a></li><li><a href="etl/README.zh.html"><strong aria-hidden="true">3.24.</strong> ETL</a></li><li><a href="accumulate/README.zh.html"><strong aria-hidden="true">3.25.</strong> 集合操作 &gt;&lt; Accumulate</a></li><li><a href="acronym/README.zh.html"><strong aria-hidden="true">3.26.</strong> 术语 &gt;&lt; Acronym</a></li><li><a href="sieve/README.zh.html"><strong aria-hidden="true">3.27.</strong> 素数筛 &gt;&lt; Sieve</a></li><li><a href="rna-transcription/README.zh.html"><strong aria-hidden="true">3.28.</strong> RNA 转录 &gt;&lt; RNA Transcription</a></li><li><a href="triangle/README.zh.html"><strong aria-hidden="true">3.29.</strong> 三角形</a></li><li><a href="roman-numerals/README.zh.html"><strong aria-hidden="true">3.30.</strong> 罗马数字 &gt;&lt; Roman Numerals</a></li><li><a href="all-your-base/README.zh.html"><strong aria-hidden="true">3.31.</strong> 你所的基本</a></li><li><a href="grade-school/README.zh.html"><strong aria-hidden="true">3.32.</strong> 学册</a></li><li><a href="binary-search/README.zh.html"><strong aria-hidden="true">3.33.</strong> 二分查找</a></li><li><a href="robot-simulator/README.zh.html"><strong aria-hidden="true">3.34.</strong> 机器人模拟器</a></li><li><a href="bracket-push/README.zh.html"><strong aria-hidden="true">3.35.</strong> 括号配套</a></li><li><a href="luhn-from/README.zh.html"><strong aria-hidden="true">3.36.</strong> Luhn From</a></li><li><a href="queen-attack/README.zh.html"><strong aria-hidden="true">3.37.</strong> 皇后 攻击</a></li><li><a href="bowling/README.zh.html"><strong aria-hidden="true">3.38.</strong> 保龄球</a></li><li><a href="sublist/README.zh.html"><strong aria-hidden="true">3.39.</strong> 子列表</a></li><li><a href="space-age/README.zh.html"><strong aria-hidden="true">3.40.</strong> 地球年</a></li><li><a href="luhn-trait/README.zh.html"><strong aria-hidden="true">3.41.</strong> Luhn Trait</a></li><li><a href="macros/README.zh.html"><strong aria-hidden="true">3.42.</strong> 宏</a></li><li><a href="allergies/README.zh.html"><strong aria-hidden="true">3.43.</strong> 过敏</a></li><li><a href="variable-length-quantity/README.zh.html"><strong aria-hidden="true">3.44.</strong> 可变长度数量</a></li><li><a href="phone-number/README.zh.html"><strong aria-hidden="true">3.45.</strong> 电话号码</a></li><li><a href="wordy/README.zh.html"><strong aria-hidden="true">3.46.</strong> 罗唆</a></li><li><a href="tournament/README.zh.html"><strong aria-hidden="true">3.47.</strong> 比赛</a></li><li><a href="custom-set/README.zh.html"><strong aria-hidden="true">3.48.</strong> 自定义 set</a></li><li><a href="alphametics/README.zh.html"><strong aria-hidden="true">3.49.</strong> 字母谜题</a></li><li><a href="two-bucket/README.zh.html"><strong aria-hidden="true">3.50.</strong> 两个桶</a></li><li><a href="pig-latin/README.zh.html"><strong aria-hidden="true">3.51.</strong> 猪的拉丁文</a></li><li><a href="diamond/README.zh.html"><strong aria-hidden="true">3.52.</strong> 钻石</a></li><li><a href="spiral-matrix/README.zh.html"><strong aria-hidden="true">3.53.</strong> 螺旋矩阵</a></li><li><a href="palindrome-products/README.zh.html"><strong aria-hidden="true">3.54.</strong> 回文产品</a></li><li><a href="poker/README.zh.html"><strong aria-hidden="true">3.55.</strong> 扑克</a></li><li><a href="grep/README.zh.html"><strong aria-hidden="true">3.56.</strong> grep</a></li><li><a href="scale-generator/README.zh.html"><strong aria-hidden="true">3.57.</strong> 音阶生成器</a></li><li><a href="decimal/README.zh.html"><strong aria-hidden="true">3.58.</strong> 十进制</a></li><li><a href="anagram/README.zh.html"><strong aria-hidden="true">3.59.</strong> 字谜</a></li><li><a href="protein-translation/README.zh.html"><strong aria-hidden="true">3.60.</strong> 蛋白质翻译</a></li><li><a href="robot-name/README.zh.html"><strong aria-hidden="true">3.61.</strong> 机器人名称</a></li><li><a href="book-store/README.zh.html"><strong aria-hidden="true">3.62.</strong> 书店</a></li></ol></li><li><a href="high.html"><strong aria-hidden="true">4.</strong> 难</a></li><li><ol class="section"><li><a href="ocr-numbers/README.zh.html"><strong aria-hidden="true">4.1.</strong> OCR 号码</a></li><li><a href="minesweeper/README.zh.html"><strong aria-hidden="true">4.2.</strong> 扫雷</a></li><li><a href="dominoes/README.zh.html"><strong aria-hidden="true">4.3.</strong> 骨牌</a></li><li><a href="parallel-letter-frequency/README.zh.html"><strong aria-hidden="true">4.4.</strong> 并行字母频率</a></li><li><a href="rectangles/README.zh.html"><strong aria-hidden="true">4.5.</strong> 矩形</a></li><li><a href="forth/README.zh.html"><strong aria-hidden="true">4.6.</strong> Forth</a></li><li><a href="circular-buffer/README.zh.html"><strong aria-hidden="true">4.7.</strong> 循环缓冲区</a></li><li><a href="react/README.zh.html"><strong aria-hidden="true">4.8.</strong> React</a></li></ol></li><li><a href="untag.html"><strong aria-hidden="true">5.</strong> 未标签</a></li><li><ol class="section"><li><a href="hexadecimal/README.zh.html"><strong aria-hidden="true">5.1.</strong> 十六进制</a></li><li><a href="nucleotide-codons/README.zh.html"><strong aria-hidden="true">5.2.</strong> 核苷酸密码子</a></li><li><a href="two-fer/README.zh.html"><strong aria-hidden="true">5.3.</strong> two-fer</a></li><li class="spacer"></li></ol></li><li><a href="add-test-code.html">修改 mdBook 主题</a></li></ol>
    </nav>

    <div id="page-wrapper" class="page-wrapper">

        <div class="page">
            
            <div id="menu-bar" class="menu-bar">
                <div id="menu-bar-sticky-container">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents"
                            aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <!-- START - Rust Cookbook customization -->
                        <button id="edit-button" class="icon-button" type="button" title="Fork and edit" aria-label="Fork and edit"
                            aria-haspopup="true" aria-expanded="false" aria-controls="edit">
                            <i class="fa fa-edit">Edit</i>
                        </button>
                        <!-- END - Rust Cookbook customization -->
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme"
                            aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light <span class="default">(default)</span></button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)"
                            aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                        
                    </div>

                    <h1 class="menu-title">exercisms.io 快速练习</h1>
                    
                        <div class="right-buttons">
                            <a href="print.html" title="Print this book" aria-label="Print this book">
                                <i id="print-button" class="fa fa-print"></i>
                            </a>
                            
                        </div>
                    </div>
                </div>

            
            <div id="search-wrapper" class="hidden">
                <form id="searchbar-outer" class="searchbar-outer">
                    <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..."
                        aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                </form>
                <div id="searchresults-outer" class="searchresults-outer hidden">
                    <div id="searchresults-header" class="searchresults-header"></div>
                    <ul id="searchresults">
                    </ul>
                </div>
            </div>
            

            <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
            <script type="text/javascript">
                document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                Array.from(document.querySelectorAll('#sidebar a')).forEach(function (link) {
                    link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                });
            </script>

            <!-- // START - Rust Cookbook customization -->
            <script>
                document.getElementById("edit-button").addEventListener("click", function () {
                    var editWindow = window.open("https://github.com/chinanf-boy/exercism-rust-zh/edit/master/src/print.md");
                });</script>
            <!-- // END - Rust Cookbook customization -->

            <div id="content" class="content">
                <main>
                    <blockquote>
<p>本库在<a href="https://github.com/chinanf-boy/exercism-rust-zh">exercism/rust 的中文翻译</a></p>
</blockquote>
<p>exercism 是一个不错的题目网站，但是它的过程并不是很方便，需要下载，构建测试才能知道，你的对错。所以有没有方便点的方式呢？</p>
<a class="header" href="#网页练习功能" id="网页练习功能"><h3>网页练习功能</h3></a>
<p>这项功能是借助<a href="https://github.com/rust-lang-nursery/mdBook">mdBook</a>工具完成的，在 mdBook 生成的静态页面中，Rust 代码可以直接执行，它的工作原理是 js 底层与 <a href="https://play.rust-lang.org">Rust 游乐场</a> API 的交互。但是，原有的实现并不是 Rust 测试模式，所以我们要改些事情。(请往下阅读)</p>
<a class="header" href="#todo" id="todo"><h2>TODO</h2></a>
<p>我们要改造的关键：</p>
<ul>
<li><code>theme/book.js</code> 改造
<ul>
<li>[x] 使用<code>cargo test</code></li>
<li>[x] 合并用户输入与测试用例</li>
</ul>
</li>
</ul>
<p>修改默认主题的<code>book.js</code>，如果你对这个修改过程感兴趣，请查阅<a href="./add-test-code.html">使用 Cargo test</a></p>
<ul>
<li>[x] 自动化测试静态页面的代码执行。</li>
</ul>
<p>为了对改造代码的有效性，有一定了解，我选择对页面进行自动化测试，我把它放在了<a href="https://github.com/chinanf-boy/exercism-rust-zh-webdriver">github 上</a>，不过我不建议你自行运行，因为会耗费时间与计算机资源，甚至无法完整通过测试(需要浏览器，打开 88 个网页)。其中借助 webdriver 测试项目，如有相关需求，可以自行了解，它的 API 还是很好用的。</p>
<a class="header" href="#说明" id="说明"><h2>说明</h2></a>
<p>每个练习网页主要分为四个部分</p>
<ul>
<li>
<ol>
<li>说明/题目</li>
</ol>
</li>
<li>
<ol start="2">
<li>未完成的代码(可编辑，直接运行就好)</li>
</ol>
</li>
<li>
<ol start="3">
<li>测试代码(不可编辑)</li>
</ol>
</li>
<li>
<ol start="4">
<li>示例答案(不可编辑，直接运行就好)</li>
</ol>
</li>
</ul>
<a class="header" href="#中文翻译列表" id="中文翻译列表"><h3>中文翻译列表</h3></a>
<p>每个练习，最初来自英文人群，所以可能在某些说明上，和我国国情并不吻合，如遇到这种情况，完全可以 Issue/PR 该 github 项目，改成符合国情的问题。</p>
<p>测试代码与未完成代码之间，会有重叠的库导入（因我会把他俩合并，扔给 Rust 游乐场），所以需要修正。</p>
<p>还有，每个练习本身，都是完整的 Cargo 项目。其中自然少不了对其他非内置箱子的导入，在这时，我能做的，只是提示你们，某某项目无法通过网页测试(因，Rust 游乐场并没有该箱子)：</p>
<ul>
<li>[x] 为中文校对，但有时出题的人，就只是搬维基百科的资料，所以，题目描述可能不是说百分百贴切。</li>
<li><code>&gt;</code> 为测试代码修正。</li>
<li><code>no</code> 具有<a href="https://github.com/integer32llc/rust-playground/blob/master/compiler/base/Cargo.toml">非内置箱子</a>，无法编译成功, 需要非内置的其他箱子，这时，只能说句“抱歉，要本机下载”。</li>
</ul>
<blockquote>
<p><a href="https://github.com/chinanf-boy/exercism-rust-zh/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc">Issue me , if you want</a></p>
</blockquote>
<a class="header" href="#a-hreflowhtml易a" id="a-hreflowhtml易a"><h3><a href="./low.html">易</a></h3></a>
<hr />
<ul>
<li>[x] <code>&gt;</code> <a href="./hello-world/README.zh.html">hello world</a></li>
<li>[x] <code>&gt;</code> <a href="./gigasecond/README.zh.html">千兆秒 &gt;&lt; Gigasecond)</a></li>
<li>[x] <code>&gt;</code> <a href="./leap/README.zh.html">闰年 &gt;&lt; Leap</a></li>
<li>[x] <code>&gt;</code> <a href="./raindrops/README.zh.html">雨滴声 &gt;&lt; Raindrops</a></li>
<li>[x] <code>&gt;</code> <a href="./reverse-string/README.zh.html">反转字符串 &gt;&lt; Reverse String</a></li>
<li>[x] <code>&gt;</code> <a href="./nth-prime/README.zh.html">第 n 个素数 &gt;&lt; Nth Prime</a></li>
<li>[x] <code>&gt;</code> <a href="./bob/README.zh.html">迟钝孩子 &gt;&lt; Bob</a></li>
<li>[x] <code>&gt;</code> <a href="./beer-song/README.zh.html">啤酒之歌 &gt;&lt; Beer Song</a></li>
<li>[x] <code>&gt;</code> <a href="./proverb/README.zh.html">谚语串烧 &gt;&lt; Proverb</a></li>
<li>[x] <code>&gt;</code> <a href="./difference-of-squares/README.zh.html">平方差 &gt;&lt; Difference Of Squares</a></li>
<li>[x] <code>&gt;</code> <a href="./sum-of-multiples/README.zh.html">倍数之和 &gt;&lt; Sum Of Multiples</a></li>
<li>[x] <code>&gt;</code> <a href="./grains/README.zh.html">谷物 &gt;&lt; Grains</a></li>
<li>[x] <code>&gt;</code> <a href="./pythagorean-triplet/README.zh.html">勾股数 &gt;&lt; Pythagorean Triplet</a></li>
<li>[x] <code>&gt;</code> <a href="./prime-factors/README.zh.html">素数因子 &gt;&lt; Prime Factors</a></li>
<li>[x] <code>&gt;</code> <a href="./series/README.zh.html">子串 &gt;&lt; Series</a></li>
<li>[x] <code>&gt;</code> <a href="./armstrong-numbers/README.zh.html">水仙花数 &gt;&lt; Armstrong Numbers</a></li>
<li>[x] <code>&gt;</code> <a href="./collatz-conjecture/README.zh.html">3n+1 猜想 &gt;&lt; Collatz Conjecture</a></li>
<li>[x] <code>&gt;</code> <a href="./diffie-hellman/README.zh.html">迪菲-赫尔曼密钥交换 &gt;&lt; Diffie Hellman</a></li>
</ul>
<a class="header" href="#a-hrefmediumhtml中等a" id="a-hrefmediumhtml中等a"><h3><a href="./medium.html">中等</a></h3></a>
<hr />
<ul>
<li>[x] <code>&gt;</code> - <a href="./saddle-points/README.zh.html">鞍点 &gt;&lt; Saddle Points</a></li>
<li>[x] <code>&gt;</code> <a href="./isogram/README.zh.html">等值线 &gt;&lt; Isogram</a></li>
<li>[x] <code>&gt;</code> <a href="./say/README.zh.html">英文说数字 &gt;&lt; Say</a></li>
<li>[x] <code>&gt;</code> <a href="./run-length-encoding/README.zh.html">游程编码 &gt;&lt; Run Length Encoding</a></li>
<li>[x] <code>&gt;</code> <a href="./isbn-verifier/README.zh.html">图书编号 &gt;&lt; ISBN Verifier</a></li>
<li>[x] <code>&gt;</code> <a href="./perfect-numbers/README.zh.html">数字也能分类 &gt;&lt; Perfect Numbers</a></li>
<li>[x] <code>&gt;</code> <a href="./clock/README.zh.html">时钟 &gt;&lt; Clock</a></li>
<li>[x] <code>no</code> <a href="./dot-dsl/README.zh.html">DOT DSL</a></li>
<li>[x] <code>&gt;</code> <a href="./hamming/README.zh.html">汉明距离 &gt;&lt; Hamming</a></li>
<li>[x] <code>&gt;</code> <a href="./simple-linked-list/README.zh.html">简单链表 &gt;&lt; Simple Linked List</a></li>
<li>[x] <code>&gt;</code> <a href="./pascals-triangle/README.zh.html">杨辉三角形 &gt;&lt; Pascal’s Triangle</a></li>
<li>[x] <code>&gt;</code> <a href="./scrabble-score/README.zh.html">字母的分数游戏 &gt;&lt; Scrabble Score</a></li>
<li>[x] <code>&gt;</code> <a href="./pangram/README.zh.html">全字母句 &gt;&lt; Pangram</a></li>
<li>[x] <code>no</code> <a href="./paasio/README.zh.html">PaaS-IO-报告 &gt;&lt; Paasio</a></li>
<li>[x] <code>&gt;</code> <a href="./nucleotide-count/README.zh.html">核苷酸计数 &gt;&lt; Nucleotide Count</a></li>
<li>[x] <code>&gt;</code> <a href="./luhn/README.zh.html">模 10 算法 &gt;&lt; Luhn</a></li>
<li>[x] <code>&gt;</code> <a href="./largest-series-product/README.zh.html">最大数字子串乘积 &gt;&lt; Largest Series Product</a></li>
<li>[x] <code>&gt;</code> <a href="./word-count/README.zh.html">单词计数 &gt;&lt; Word Count</a></li>
<li>[x] <code>&gt;</code> <a href="./atbash-cipher/README.zh.html">Atbash 加密 &gt;&lt; Atbash Cipher</a></li>
<li>[x] <code>&gt;</code> <a href="./crypto-square/README.zh.html">密码矩形 &gt;&lt; Crypto Square</a></li>
<li>[x] <code>&gt;</code> <a href="./rotational-cipher/README.zh.html">旋转密码 &gt;&lt; Rotational Cipher</a></li>
<li>[x] <code>&gt;</code> <a href="./simple-cipher/README.zh.html">简单加密 &gt;&lt; Simple Cipher</a></li>
<li>[x] <code>&gt;</code> <a href="./rail-fence-cipher/README.zh.html">栅栏密码 &gt;&lt; Rail Fence Cipher</a></li>
<li>[x] <code>&gt;</code> <a href="./etl/README.zh.html">ETL</a></li>
<li>[x] <code>&gt;</code> <a href="./accumulate/README.zh.html">集合操作 &gt;&lt; Accumulate</a></li>
<li>[x] <code>&gt;</code> <a href="./acronym/README.zh.html">术语 &gt;&lt; Acronym</a></li>
<li>[x] <code>&gt;</code> <a href="./sieve/README.zh.html">素数筛 &gt;&lt; Sieve</a></li>
<li>[x] <code>&gt;</code> <a href="./rna-transcription/README.zh.html">RNA 转录 &gt;&lt; RNA Transcription</a></li>
<li>[x] <code>&gt;</code> <a href="./triangle/README.zh.html">三角形</a></li>
<li>[x] <code>&gt;</code> <a href="./roman-numerals/README.zh.html">罗马数字 &gt;&lt; Roman Numerals</a></li>
<li>[x] <code>&gt;</code> <a href="./all-your-base/README.zh.html">你所的基本</a></li>
<li>[x] <code>&gt;</code> <a href="./grade-school/README.zh.html">学册</a></li>
<li>[x] <code>&gt;</code> <a href="./binary-search/README.zh.html">二分查找</a></li>
<li>[x] <code>&gt;</code> <a href="./robot-simulator/README.zh.html">机器人模拟器</a></li>
<li>[x] <code>&gt;</code> <a href="./bracket-push/README.zh.html">括号配套</a></li>
<li>[x] <code>&gt;</code> <a href="./luhn-from/README.zh.html">Luhn From</a></li>
<li>[x] <code>&gt;</code> <a href="./queen-attack/README.zh.html">皇后 攻击</a></li>
<li>[x] <code>&gt;</code> <a href="./bowling/README.zh.html">保龄球</a></li>
<li>[x] <code>&gt;</code> <a href="./sublist/README.zh.html">子列表</a></li>
<li>[x] <code>&gt;</code> <a href="./space-age/README.zh.html">地球年</a></li>
<li>[x] <code>&gt;</code> <a href="./luhn-trait/README.zh.html">Luhn Trait</a></li>
<li>[x] <code>&gt;</code> <a href="./macros/README.zh.html">宏</a></li>
<li>[x] <code>&gt;</code> <a href="./allergies/README.zh.html">过敏</a></li>
<li>[x] <code>&gt;</code> <a href="./variable-length-quantity/README.zh.html">可变长度数量</a></li>
<li>[x] <code>&gt;</code> <a href="./phone-number/README.zh.html">电话号码</a></li>
<li>[x] <code>&gt;</code> <a href="./wordy/README.zh.html">罗唆</a></li>
<li>[x] <code>&gt;</code> <a href="./tournament/README.zh.html">比赛</a></li>
<li>[x] <code>&gt;</code> <a href="./custom-set/README.zh.html">自定义 set</a></li>
<li>[x] <code>no</code> <a href="./alphametics/README.zh.html">字母谜题</a></li>
<li>[x] <code>&gt;</code> <a href="./two-bucket/README.zh.html">两个桶</a></li>
<li>[x] <code>&gt;</code> <a href="./pig-latin/README.zh.html">猪的拉丁文</a></li>
<li>[x] <code>&gt;</code> <a href="./diamond/README.zh.html">钻石</a></li>
<li>[x] <code>&gt;</code> <a href="./spiral-matrix/README.zh.html">螺旋矩阵</a></li>
<li>[x] <code>&gt;</code> <a href="./palindrome-products/README.zh.html">回文产品</a></li>
<li>[x] <code>no</code> <a href="./poker/README.zh.html">扑克</a></li>
<li>[x] <code>&gt;</code> <a href="./grep/README.zh.html">grep</a></li>
<li>[x] <code>no</code> <a href="./scale-generator/README.zh.html">音阶生成器</a></li>
<li>[x] <code>no</code> <a href="./decimal/README.zh.html">十进制</a></li>
<li>[x] <code>&gt;</code> <a href="./anagram/README.zh.html">字谜</a></li>
<li>[x] <code>&gt;</code> <a href="./protein-translation/README.zh.html">蛋白质翻译</a></li>
<li>[x] <code>&gt;</code> <a href="./robot-name/README.zh.html">机器人名称</a></li>
<li>[x] <code>&gt;</code> <a href="./book-store/README.zh.html">书店</a></li>
</ul>
<a class="header" href="#a-hrefhighhtml难a" id="a-hrefhighhtml难a"><h3><a href="./high.html">难</a></h3></a>
<hr />
<ul>
<li>[x] <code>&gt;</code> <a href="./ocr-numbers/README.zh.html">OCR 号码</a></li>
<li>[x] <code>&gt;</code> <a href="./minesweeper/README.zh.html">扫雷</a></li>
<li>[x] <code>&gt;</code> <a href="./dominoes/README.zh.html">骨牌</a></li>
<li>[x] <code>&gt;</code> <a href="./parallel-letter-frequency/README.zh.html">并行字母频率</a></li>
<li>[x] <code>&gt;</code> <a href="./rectangles/README.zh.html">矩形</a></li>
<li>[x] <code>&gt;</code> <a href="./forth/README.zh.html">Forth</a></li>
<li>[x] <code>&gt;</code> <a href="./circular-buffer/README.zh.html">循环缓冲区</a></li>
<li>[x] <code>&gt;</code> <a href="./react/README.zh.html">React</a></li>
</ul>
<a class="header" href="#a-hrefuntaghtml还没标签a" id="a-hrefuntaghtml还没标签a"><h3><a href="./untag.html">还没标签</a></h3></a>
<ul>
<li>[x] <code>&gt;</code> <a href="./hexadecimal/README.zh.html">十六进制</a></li>
<li>[x] <code>&gt;</code> <a href="./nucleotide-codons/README.zh.html">核苷酸密码子</a></li>
<li>[x] <code>&gt;</code> <a href="./two-fer/README.zh.html">two-fer</a></li>
</ul>
<a class="header" href="#易" id="易"><h1>易</h1></a>
<ul>
<li><a href="./hello-world/README.zh.html">hello world</a></li>
<li><a href="./gigasecond/README.zh.html">千兆秒-Gigasecond</a></li>
<li><a href="./leap/README.zh.html">闰年-Leap</a></li>
<li><a href="./raindrops/README.zh.html">雨滴声-Raindrops</a></li>
<li><a href="./reverse-string/README.zh.html">反转字符串-Reverse String</a></li>
<li><a href="./nth-prime/README.zh.html">第n个素数-Nth Prime</a></li>
<li><a href="./bob/README.zh.html">迟钝孩子-Bob</a></li>
<li><a href="./beer-song/README.zh.html">啤酒之歌-Beer Song</a></li>
<li><a href="./proverb/README.zh.html">谚语串烧-Proverb</a></li>
<li><a href="./difference-of-squares/README.zh.html">平方差-Difference Of Squares</a></li>
<li><a href="./sum-of-multiples/README.zh.html">Sum Of Multiples</a></li>
<li><a href="./grains/README.zh.html">Grains</a></li>
<li><a href="./pythagorean-triplet/README.zh.html">Pythagorean Triplet</a></li>
<li><a href="./prime-factors/README.zh.html">Prime Factors</a></li>
<li><a href="./series/README.zh.html">Series</a></li>
<li><a href="./armstrong-numbers/README.zh.html">Armstrong Numbers</a></li>
<li><a href="./collatz-conjecture/README.zh.html">Collatz Conjecture</a></li>
<li><a href="./diffie-hellman/README.zh.html">Diffie Hellman</a></li>
</ul>
<a class="header" href="#hello-world" id="hello-world"><h1>hello world</h1></a>
<a class="header" href="#1-readme" id="1-readme"><h2>1. Readme</h2></a>
<a class="header" href="#你好世界" id="你好世界"><h1>你好世界</h1></a>
<p>经典的介绍性练习.只要说”Hello, World!”.</p>
<ul>
<li>如有需要请看<a href="hello-world/./GETTING_STARTED.zh.html">小小的入门</a></li>
</ul>
<p><a href="http://en.wikipedia.org/wiki/%22Hello,_world!%22_program">“Hello, World!”</a>是在新的语言或环境中开始编程的第一个程序的传统.</p>
<p>目标很简单:</p>
<ul>
<li>编写一个返回字符串”Hello,World!”的函数.</li>
<li>运行测试套件，并确保测试成功.</li>
<li>提交您的解决方案，并在网站上查看.</li>
</ul>
<p>如果一切顺利,你将准备好进行第一次真正的锻炼.</p>
<a class="header" href="#资源" id="资源"><h2>资源</h2></a>
<p>这是一个介绍<a href="http://en.wikipedia.org/wiki/%22Hello,_world!%22_program">http://en.wikipedia.org/wiki/%22Hello,_world!%22_program</a>使用者，使用Exercism进行练习.</p>
<a class="header" href="#2-开始你的表演" id="2-开始你的表演"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">// The &amp;'static here means the return type has a static lifetime.
// This is a Rust feature that you don't need to worry about now.
pub fn hello() -&gt; &amp;'static str {
   &quot;Goodbye, World!&quot;
}
</code></pre></pre>
<a class="header" href="#3-测试代码查看" id="3-测试代码查看"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]


#fn main() {
#[test]
fn test_hello_world() {
   assert_eq!(&quot;Hello, World!&quot;, hello());
}

#}</code></pre></pre>
<a class="header" href="#4-答案" id="4-答案"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn hello() -&gt; &amp;'static str {
   &quot;Hello, World!&quot;
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关" id="填充相关"><h2>填充/相关</h2></a>
<a class="header" href="#千兆秒-gigasecond" id="千兆秒-gigasecond"><h1>千兆秒-Gigasecond</h1></a>
<a class="header" href="#1-readme-1" id="1-readme-1"><h2>1. Readme</h2></a>
<a class="header" href="#gigasecond" id="gigasecond"><h1>Gigasecond</h1></a>
<p>计算某个开始时刻，计算10^9秒后的时刻.</p>
<p>一个 <code>千兆秒-gigasecond</code> 是10^9(1,000,000,000)秒.</p>
<p>如果您不确定<code>DateTime&lt;Utc&gt;</code>可以执行哪些操作，看看<a href="https://docs.rs/chrono/0.4.0/chrono/">chrono crate</a> - 它在<code>Cargo.toml</code>，被列为本练习的一个依赖项.</p>
<a class="header" href="#source" id="source"><h2>Source</h2></a>
<p>Chapter 9 in Chris Pine’s online Learn to Program tutorial. <a href="http://pine.fm/LearnToProgram/?Chapter=09">http://pine.fm/LearnToProgram/?Chapter=09</a></p>
<a class="header" href="#2-开始你的表演-1" id="2-开始你的表演-1"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">extern crate chrono;
use chrono::{DateTime, Utc};

// Returns a Utc DateTime one billion seconds after start.
pub fn after(start: DateTime&lt;Utc&gt;) -&gt; DateTime&lt;Utc&gt; {
   unimplemented!(&quot;What time is a gigasecond later than {}&quot;, start);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-1" id="3-测试代码查看-1"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// extern crate chrono;
use chrono::TimeZone;

#[test]
fn test_date() {
   let start_date = Utc.ymd(2011, 4, 25).and_hms(0, 0, 0);

   assert_eq!(after(start_date), Utc.ymd(2043, 1, 1).and_hms(1, 46, 40));
}

#[test]
//#[ignore]
fn test_another_date() {
   let start_date = Utc.ymd(1977, 6, 13).and_hms(0, 0, 0);

   assert_eq!(after(start_date), Utc.ymd(2009, 2, 19).and_hms(1, 46, 40));
}

#[test]
//#[ignore]
fn test_third_date() {
   let start_date = Utc.ymd(1959, 7, 19).and_hms(0, 0, 0);

   assert_eq!(after(start_date), Utc.ymd(1991, 3, 27).and_hms(1, 46, 40));
}

#[test]
//#[ignore]
fn test_datetime() {
   let start_date = Utc.ymd(2015, 1, 24).and_hms(22, 0, 0);

   assert_eq!(after(start_date), Utc.ymd(2046, 10, 2).and_hms(23, 46, 40));
}

#[test]
//#[ignore]
fn test_another_datetime() {
   let start_date = Utc.ymd(2015, 1, 24).and_hms(23, 59, 59);

   assert_eq!(after(start_date), Utc.ymd(2046, 10, 3).and_hms(1, 46, 39));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-1" id="4-答案-1"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
extern crate chrono;
use chrono::{DateTime, Duration, Utc};

pub fn after(start: DateTime&lt;Utc&gt;) -&gt; DateTime&lt;Utc&gt; {
   start + Duration::seconds(1_000_000_000)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-1" id="填充相关-1"><h2>填充/相关</h2></a>
<a class="header" href="#闰年-leap" id="闰年-leap"><h1>闰年-Leap</h1></a>
<a class="header" href="#1-readme-2" id="1-readme-2"><h2>1. Readme</h2></a>
<a class="header" href="#leap" id="leap"><h1>Leap</h1></a>
<p>给出年份,报告是不是闰年.</p>
<p>这里的棘手问题是公历中，闰年计算:</p>
<blockquote>
<p>我想也很清楚了，就不译了</p>
</blockquote>
<pre><code class="language-text">on every year that is evenly divisible by 4
  except every year that is evenly divisible by 100
    unless the year is also evenly divisible by 400
</code></pre>
<p>例如,1997不是闰年,而是1996是，1900不是闰年,而2000是。</p>
<p>如果在您的语言标准库中，提供了执行此实现的方法, 请假装它不存在,并自己实现它.</p>
<a class="header" href="#笔记" id="笔记"><h2>笔记</h2></a>
<p>虽然我们的采用一些非常简单的规则,但还有更多的东西要学!</p>
<p>为了一个令人愉快的,为什么有闰年现象的解释,请观看<a href="http://www.youtube.com/watch?v=xX96xng7sAE">这个YouTube视频</a>.</p>
<blockquote>
<p>译: 我给个<strong>李永乐老师的视频</strong>:&gt;<a href="https://www.youtube.com/watch?v=dbPmMDiKW-g">youtube</a> :&gt; <a href="https://www.bilibili.com/video/av28872608?from=search&amp;seid=4068395089995838126">bilibili</a></p>
</blockquote>
<a class="header" href="#source-1" id="source-1"><h2>Source</h2></a>
<p>JavaRanch Cattle Drive, exercise 3 <a href="http://www.javaranch.com/leap.jsp">http://www.javaranch.com/leap.jsp</a></p>
<a class="header" href="#2-开始你的表演-2" id="2-开始你的表演-2"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn is_leap_year(year: i32) -&gt; bool {
   unimplemented!(&quot;true if {} is a leap year&quot;, year)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-2" id="3-测试代码查看-2"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_vanilla_leap_year() {
   assert_eq!(is_leap_year(1996), true);
}

#[test]
//#[ignore]
fn test_any_old_year() {
   assert_eq!(is_leap_year(1997), false);
}

#[test]
//#[ignore]
fn test_century() {
   assert_eq!(is_leap_year(1700), false);
   assert_eq!(is_leap_year(1800), false);
   assert_eq!(is_leap_year(1900), false);
}

#[test]
//#[ignore]
fn test_exceptional_centuries() {
   assert_eq!(is_leap_year(1600), true);
   assert_eq!(is_leap_year(2000), true);
   assert_eq!(is_leap_year(2400), true);
}

#[test]
//#[ignore]
fn test_years_1600_to_1699() {
   let incorrect_years = (1600..1700)
       .filter(|&amp;year| is_leap_year(year) != (year % 4 == 0))
       .collect::&lt;Vec&lt;_&gt;&gt;();

   if !incorrect_years.is_empty() {
       panic!(&quot;incorrect result for years: {:?}&quot;, incorrect_years);
   }
}

#}</code></pre></pre>
<a class="header" href="#4-答案-2" id="4-答案-2"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn is_leap_year(year: i32) -&gt; bool {
   let has_factor = |n| year % n == 0;
   has_factor(4) &amp;&amp; (!has_factor(100) || has_factor(400))
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-2" id="填充相关-2"><h2>填充/相关</h2></a>
<a class="header" href="#雨滴声-raindrops" id="雨滴声-raindrops"><h1>雨滴声-Raindrops</h1></a>
<a class="header" href="#1-readme-3" id="1-readme-3"><h2>1. Readme</h2></a>
<a class="header" href="#雨滴-raindrops" id="雨滴-raindrops"><h1>雨滴-Raindrops</h1></a>
<p>把一个数字转换成一个字符串,它的内容取决于，数字的因素.</p>
<ul>
<li>如果数字有 3 作为一个因素,输出”Pling”.</li>
<li>如果数字有 5 作为一个因素,输出”Plang’”.</li>
<li>如果数字有 7 作为一个因素,输出”Plong”.</li>
<li>如果数字没有 3, 5,或 7 作为一个因素, 直接给数字。</li>
</ul>
<a class="header" href="#实例" id="实例"><h2>实例</h2></a>
<ul>
<li>28 的因素是 1, 2, 4, <strong>7</strong>,14, 28.
<ul>
<li>雨滴说,这将是一个简单的”Plong”.</li>
</ul>
</li>
<li>30 的因素是 1, 2,<strong>3</strong>,<strong>5</strong>,6, 10, 15,30.
<ul>
<li>雨滴说,这将是一个”PlingPlang”.</li>
</ul>
</li>
<li>34 有四个因素:1, 2, 17,34.
<ul>
<li>雨滴说,这将是”34”.</li>
</ul>
</li>
</ul>
<a class="header" href="#source-2" id="source-2"><h2>Source</h2></a>
<p>A variation on a famous interview question intended to weed out potential candidates. <a href="http://jumpstartlab.com">http://jumpstartlab.com</a></p>
<a class="header" href="#2-开始你的表演-3" id="2-开始你的表演-3"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn raindrops(n: u32) -&gt; String {
   unimplemented!(&quot;what sound does Raindrop #{} make?&quot;, n)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-3" id="3-测试代码查看-3"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_1() {
   assert_eq!(&quot;1&quot;, raindrops(1));
}

#[test]
//#[ignore]
fn test_3() {
   assert_eq!(&quot;Pling&quot;, raindrops(3));
}

#[test]
//#[ignore]
fn test_5() {
   assert_eq!(&quot;Plang&quot;, raindrops(5));
}

#[test]
//#[ignore]
fn test_7() {
   assert_eq!(&quot;Plong&quot;, raindrops(7));
}

#[test]
//#[ignore]
fn test_6() {
   assert_eq!(&quot;Pling&quot;, raindrops(6));
}

#[test]
//#[ignore]
fn test_8() {
   assert_eq!(&quot;8&quot;, raindrops(8));
}

#[test]
//#[ignore]
fn test_9() {
   assert_eq!(&quot;Pling&quot;, raindrops(9));
}

#[test]
//#[ignore]
fn test_10() {
   assert_eq!(&quot;Plang&quot;, raindrops(10));
}

#[test]
//#[ignore]
fn test_14() {
   assert_eq!(&quot;Plong&quot;, raindrops(14));
}

#[test]
//#[ignore]
fn test_15() {
   assert_eq!(&quot;PlingPlang&quot;, raindrops(15));
}

#[test]
//#[ignore]
fn test_21() {
   assert_eq!(&quot;PlingPlong&quot;, raindrops(21));
}

#[test]
//#[ignore]
fn test_25() {
   assert_eq!(&quot;Plang&quot;, raindrops(25));
}

#[test]
//#[ignore]
fn test_27() {
   assert_eq!(&quot;Pling&quot;, raindrops(27));
}

#[test]
//#[ignore]
fn test_35() {
   assert_eq!(&quot;PlangPlong&quot;, raindrops(35));
}

#[test]
//#[ignore]
fn test_49() {
   assert_eq!(&quot;Plong&quot;, raindrops(49));
}

#[test]
//#[ignore]
fn test_52() {
   assert_eq!(&quot;52&quot;, raindrops(52));
}

#[test]
//#[ignore]
fn test_105() {
   assert_eq!(&quot;PlingPlangPlong&quot;, raindrops(105));
}

#[test]
//#[ignore]
fn test_3125() {
   assert_eq!(&quot;Plang&quot;, raindrops(3125));
}

#[test]
//#[ignore]
fn test_12121() {
   assert_eq!(&quot;12121&quot;, raindrops(12121));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-3" id="4-答案-3"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn raindrops(n: u32) -&gt; String {
   let is_pling = |n| n % 3 == 0;
   let is_plang = |n| n % 5 == 0;
   let is_plong = |n| n % 7 == 0;
   let mut drops = String::new();
   if is_pling(n) {
       drops.push_str(&quot;Pling&quot;);
   }
   if is_plang(n) {
       drops.push_str(&quot;Plang&quot;);
   }
   if is_plong(n) {
       drops.push_str(&quot;Plong&quot;);
   }
   if drops.is_empty() {
       let s = format!(&quot;{}&quot;, n);
       drops.push_str(&amp;s);
   }
   drops
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-3" id="填充相关-3"><h2>填充/相关</h2></a>
<a class="header" href="#反转字符串-reverse-string" id="反转字符串-reverse-string"><h1>反转字符串-Reverse String</h1></a>
<a class="header" href="#1-readme-4" id="1-readme-4"><h2>1. Readme</h2></a>
<a class="header" href="#反向的字符串" id="反向的字符串"><h1>反向的字符串</h1></a>
<p>反向的字符串</p>
<p>例如:</p>
<ul>
<li>input: “cool”</li>
<li>output: “looc”</li>
</ul>
<a class="header" href="#加分" id="加分"><h2>加分</h2></a>
<p>用这个字符串:<code>uüu</code>测试你的函数, 看会发生什么。试着写一个函数,这恰当地反转这个字符串。提示: {<code>grapheme clusters</code>}</p>
<p>要拿到加分，需要测试加分项, 从最后一个测试中移除(<code>#[ignore]</code>)标志),并运行下面测试命令:</p>
<pre><code class="language-bash">$ cargo test --features grapheme
</code></pre>
<a class="header" href="#source-3" id="source-3"><h2>Source</h2></a>
<p>Introductory challenge to reverse an input string <a href="https://medium.freecodecamp.org/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb">https://medium.freecodecamp.org/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb</a></p>
<a class="header" href="#2-开始你的表演-4" id="2-开始你的表演-4"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn reverse(input: &amp;str) -&gt; String {
   unimplemented!(&quot;Write a function to reverse {}&quot;, input);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-4" id="3-测试代码查看-4"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
/// Tests for reverse-string
///
/// Generated by [script][script] using [canonical data][canonical-data]
///
/// [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
/// [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_data.json

/// Process a single test case for the property `reverse`
fn process_reverse_case(input: &amp;str, expected: &amp;str) {
   assert_eq!(&amp;reverse(input), expected)
}

#[test]
/// empty string
fn test_empty_string() {
   process_reverse_case(&quot;&quot;, &quot;&quot;);
}

#[test]
//#[ignore]
/// a word
fn test_a_word() {
   process_reverse_case(&quot;robot&quot;, &quot;tobor&quot;);
}

#[test]
//#[ignore]
/// a capitalized word
fn test_a_capitalized_word() {
   process_reverse_case(&quot;Ramen&quot;, &quot;nemaR&quot;);
}

#[test]
//#[ignore]
/// a sentence with punctuation
fn test_a_sentence_with_punctuation() {
   process_reverse_case(&quot;I'm hungry!&quot;, &quot;!yrgnuh m'I&quot;);
}

#[test]
//#[ignore]
/// a palindrome
fn test_a_palindrome() {
   process_reverse_case(&quot;racecar&quot;, &quot;racecar&quot;);
}

#[test]
//#[ignore]
/// wide characters
fn test_wide_characters() {
   process_reverse_case(&quot;子猫&quot;, &quot;猫子&quot;);
}

#[test]
//#[ignore]
#[cfg(feature = &quot;grapheme&quot;)]
/// grapheme clusters
fn test_grapheme_clusters() {
   process_reverse_case(&quot;uüu&quot;, &quot;uüu&quot;);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-4" id="4-答案-4"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
//! Example implementation for reverse-string

pub fn reverse(input: &amp;str) -&gt; String {
   let mut output = String::with_capacity(input.len());
   output.extend(input.chars().rev());
   output
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-4" id="填充相关-4"><h2>填充/相关</h2></a>
<a class="header" href="#第n个素数-nth-prime" id="第n个素数-nth-prime"><h1>第n个素数-Nth Prime</h1></a>
<a class="header" href="#1-readme-5" id="1-readme-5"><h2>1. Readme</h2></a>
<a class="header" href="#第n个素数" id="第n个素数"><h1>第n个素数</h1></a>
<p>给定一个数<code>n</code>,确定第<code>n</code>个素数是什么.</p>
<p>如: 列出前六个素数:<code>2, 3, 5、7, 11和13</code>,我们可以看到第六素数是<code>13</code>.</p>
<p>如果您的语言标准库中提供了处理素数的方法,请假装它们不存在,并自己实现它们.</p>
<a class="header" href="#source-4" id="source-4"><h2>Source</h2></a>
<p>A variation on Problem 7 at Project Euler <a href="http://projecteuler.net/problem=7">http://projecteuler.net/problem=7</a></p>
<a class="header" href="#2-开始你的表演-5" id="2-开始你的表演-5"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn nth(n: u32) -&gt; u32 {
   unimplemented!(&quot;What is the 0-indexed {}th prime number?&quot;, n)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-5" id="3-测试代码查看-5"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_first_prime() {
   assert_eq!(nth(0), 2);
}

#[test]
//#[ignore]
fn test_second_prime() {
   assert_eq!(nth(1), 3);
}

#[test]
//#[ignore]
fn test_sixth_prime() {
   assert_eq!(nth(5), 13);
}

#[test]
//#[ignore]
fn test_big_prime() {
   assert_eq!(nth(10000), 104743);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-5" id="4-答案-5"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn is_prime(n: u32) -&gt; bool {
   let mut i = 3;
   while (i * i) &lt; (n + 1) {
       if n % i == 0 {
           return false;
       }
       i += 1;
   }
   return true;
}

pub fn nth(n: u32) -&gt; u32 {
   if n == 0 {
       2
   } else {
       let mut count = 0;
       let mut candidate = 1;
       while count &lt; n {
           candidate += 2;
           if is_prime(candidate) {
               count += 1;
           }
       }
       candidate
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-5" id="填充相关-5"><h2>填充/相关</h2></a>
<a class="header" href="#迟钝孩子-bob" id="迟钝孩子-bob"><h1>迟钝孩子-Bob</h1></a>
<a class="header" href="#1-readme-6" id="1-readme-6"><h2>1. Readme</h2></a>
<a class="header" href="#鲍勃-bob" id="鲍勃-bob"><h1>鲍勃-bob</h1></a>
<p>鲍伯是一个懒散的青少年.在谈话中,他的反应非常有限.</p>
<ul>
<li>
<p>鲍伯回答:”Sure.”，如果你问他一个问题.</p>
</li>
<li>
<p>他回答:”Whoa, chill out!”，如果你对他大喊大叫.</p>
</li>
<li>
<p>他回答”Calm down, I know what I’m doing!”，如果你大声问他问题.</p>
</li>
<li>
<p>他说”Fine. Be that way!”，如果你喊他,而不说任何话.</p>
</li>
<li>
<p>他回答”Whatever”，给剩下的对话</p>
</li>
</ul>
<p>鲍勃的对话伙伴，在书面交流方面是一个纯粹主义者,并且总是遵循关于 <em>英语句子标点</em> 的通用规则.</p>
<a class="header" href="#source-5" id="source-5"><h2>Source</h2></a>
<p>Inspired by the ‘Deaf Grandma’ exercise in Chris Pine’s Learn to Program tutorial. <a href="http://pine.fm/LearnToProgram/?Chapter=06">http://pine.fm/LearnToProgram/?Chapter=06</a></p>
<a class="header" href="#2-开始你的表演-6" id="2-开始你的表演-6"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn reply(message: &amp;str) -&gt; &amp;str {
   unimplemented!(&quot;have Bob reply to the incoming message: {}&quot;, message)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-6" id="3-测试代码查看-6"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_stating_something() {
   assert_eq!(&quot;Whatever.&quot;, reply(&quot;Tom-ay-to, tom-aaaah-to.&quot;));
}

#[test]
//#[ignore]
fn test_shouting() {
   assert_eq!(&quot;Whoa, chill out!&quot;, reply(&quot;WATCH OUT!&quot;));
}

#[test]
//#[ignore]
fn test_shouting_gibberish() {
   assert_eq!(&quot;Whoa, chill out!&quot;, reply(&quot;FCECDFCAAB&quot;));
}

#[test]
//#[ignore]
fn test_asking() {
   assert_eq!(
       &quot;Sure.&quot;,
       reply(&quot;Does this cryogenic chamber make me look fat?&quot;)
   );
}

#[test]
//#[ignore]
fn test_ask_numeric_question() {
   assert_eq!(&quot;Sure.&quot;, reply(&quot;You are, what, like 15?&quot;));
}

#[test]
//#[ignore]
fn test_asking_gibberish() {
   assert_eq!(&quot;Sure.&quot;, reply(&quot;fffbbcbeab?&quot;));
}

#[test]
//#[ignore]
fn test_exclaiming() {
   assert_eq!(&quot;Whatever.&quot;, reply(&quot;Let's go make out behind the gym!&quot;));
}

#[test]
//#[ignore]
fn test_using_acronyms_in_regular_speech() {
   assert_eq!(
       &quot;Whatever.&quot;,
       reply(&quot;It's OK if you don't want to go to the DMV.&quot;)
   );
}

#[test]
//#[ignore]
fn test_forceful_question() {
   assert_eq!(
       &quot;Calm down, I know what I'm doing!&quot;,
       reply(&quot;WHAT THE HELL WERE YOU THINKING?&quot;)
   );
}

#[test]
//#[ignore]
fn test_shouting_numbers() {
   assert_eq!(&quot;Whoa, chill out!&quot;, reply(&quot;1, 2, 3 GO!&quot;));
}

#[test]
//#[ignore]
fn test_only_numbers() {
   assert_eq!(&quot;Whatever.&quot;, reply(&quot;1, 2, 3&quot;));
}

#[test]
//#[ignore]
fn test_question_with_only_numbers() {
   assert_eq!(&quot;Sure.&quot;, reply(&quot;4?&quot;));
}

#[test]
//#[ignore]
fn test_shouting_with_special_characters() {
   assert_eq!(
       &quot;Whoa, chill out!&quot;,
       reply(&quot;ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!&quot;)
   );
}

#[test]
//#[ignore]
fn test_shouting_with_no_exclamation_mark() {
   assert_eq!(&quot;Whoa, chill out!&quot;, reply(&quot;I HATE YOU&quot;));
}

#[test]
//#[ignore]
fn test_statement_containing_question_mark() {
   assert_eq!(&quot;Whatever.&quot;, reply(&quot;Ending with ? means a question.&quot;));
}

#[test]
//#[ignore]
fn test_non_letters_with_question() {
   assert_eq!(&quot;Sure.&quot;, reply(&quot;:) ?&quot;));
}

#[test]
//#[ignore]
fn test_prattling_on() {
   assert_eq!(&quot;Sure.&quot;, reply(&quot;Wait! Hang on. Are you going to be OK?&quot;));
}

#[test]
//#[ignore]
fn test_silence() {
   assert_eq!(&quot;Fine. Be that way!&quot;, reply(&quot;&quot;));
}

#[test]
//#[ignore]
fn test_prolonged_silence() {
   assert_eq!(&quot;Fine. Be that way!&quot;, reply(&quot;          &quot;));
}

#[test]
//#[ignore]
fn test_alternate_silence() {
   assert_eq!(&quot;Fine. Be that way!&quot;, reply(&quot;\t\t\t\t\t\t\t\t\t\t&quot;));
}

#[test]
//#[ignore]
fn test_multiple_line_question() {
   assert_eq!(
       &quot;Whatever.&quot;,
       reply(&quot;\nDoes this cryogenic chamber make me look fat?\nno&quot;)
   );
}

#[test]
//#[ignore]
fn test_starting_with_whitespace() {
   assert_eq!(&quot;Whatever.&quot;, reply(&quot;         hmmmmmmm...&quot;));
}

#[test]
//#[ignore]
fn test_ending_with_whitespace() {
   assert_eq!(&quot;Sure.&quot;, reply(&quot;Okay if like my  spacebar  quite a bit?   &quot;));
}

#[test]
//#[ignore]
fn test_other_whitespace() {
   assert_eq!(&quot;Fine. Be that way!&quot;, reply(&quot;\n\r \t&quot;));
}

#[test]
//#[ignore]
fn test_non_question_ending_with_whitespace() {
   assert_eq!(
       &quot;Whatever.&quot;,
       reply(&quot;This is a statement ending with whitespace      &quot;)
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-6" id="4-答案-6"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn reply(message: &amp;str) -&gt; &amp;str {
   if is_silence(message) {
       &quot;Fine. Be that way!&quot;
   } else if is_yelling(message) &amp;&amp; is_question(message) {
       &quot;Calm down, I know what I'm doing!&quot;
   } else if is_yelling(message) {
       &quot;Whoa, chill out!&quot;
   } else if is_question(message) {
       &quot;Sure.&quot;
   } else {
       &quot;Whatever.&quot;
   }
}

fn is_silence(message: &amp;str) -&gt; bool {
   message.trim().is_empty()
}

fn is_yelling(message: &amp;str) -&gt; bool {
   let s = message.trim_matches(|c: char| !c.is_alphabetic());
   !s.is_empty() &amp;&amp; s.to_uppercase() == s
}

fn is_question(message: &amp;str) -&gt; bool {
   message.trim_right().ends_with(&quot;?&quot;)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-6" id="填充相关-6"><h2>填充/相关</h2></a>
<a class="header" href="#啤酒之歌-beer-song" id="啤酒之歌-beer-song"><h1>啤酒之歌-Beer Song</h1></a>
<a class="header" href="#1-readme-7" id="1-readme-7"><h2>1. Readme</h2></a>
<a class="header" href="#啤酒之歌" id="啤酒之歌"><h1>啤酒之歌</h1></a>
<p>背诵那首备受喜爱的经典歌词,即去实地考察时的最爱: 墙上的 99 瓶啤酒.</p>
<p>请注意,并非所有歌词都相同.</p>
<pre><code class="language-text">99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.

96 bottles of beer on the wall, 96 bottles of beer.
Take one down and pass it around, 95 bottles of beer on the wall.

95 bottles of beer on the wall, 95 bottles of beer.
Take one down and pass it around, 94 bottles of beer on the wall.

94 bottles of beer on the wall, 94 bottles of beer.
Take one down and pass it around, 93 bottles of beer on the wall.

93 bottles of beer on the wall, 93 bottles of beer.
Take one down and pass it around, 92 bottles of beer on the wall.

92 bottles of beer on the wall, 92 bottles of beer.
Take one down and pass it around, 91 bottles of beer on the wall.

91 bottles of beer on the wall, 91 bottles of beer.
Take one down and pass it around, 90 bottles of beer on the wall.

90 bottles of beer on the wall, 90 bottles of beer.
Take one down and pass it around, 89 bottles of beer on the wall.

89 bottles of beer on the wall, 89 bottles of beer.
Take one down and pass it around, 88 bottles of beer on the wall.

88 bottles of beer on the wall, 88 bottles of beer.
Take one down and pass it around, 87 bottles of beer on the wall.

87 bottles of beer on the wall, 87 bottles of beer.
Take one down and pass it around, 86 bottles of beer on the wall.

86 bottles of beer on the wall, 86 bottles of beer.
Take one down and pass it around, 85 bottles of beer on the wall.

85 bottles of beer on the wall, 85 bottles of beer.
Take one down and pass it around, 84 bottles of beer on the wall.

84 bottles of beer on the wall, 84 bottles of beer.
Take one down and pass it around, 83 bottles of beer on the wall.

83 bottles of beer on the wall, 83 bottles of beer.
Take one down and pass it around, 82 bottles of beer on the wall.

82 bottles of beer on the wall, 82 bottles of beer.
Take one down and pass it around, 81 bottles of beer on the wall.

81 bottles of beer on the wall, 81 bottles of beer.
Take one down and pass it around, 80 bottles of beer on the wall.

80 bottles of beer on the wall, 80 bottles of beer.
Take one down and pass it around, 79 bottles of beer on the wall.

79 bottles of beer on the wall, 79 bottles of beer.
Take one down and pass it around, 78 bottles of beer on the wall.

78 bottles of beer on the wall, 78 bottles of beer.
Take one down and pass it around, 77 bottles of beer on the wall.

77 bottles of beer on the wall, 77 bottles of beer.
Take one down and pass it around, 76 bottles of beer on the wall.

76 bottles of beer on the wall, 76 bottles of beer.
Take one down and pass it around, 75 bottles of beer on the wall.

75 bottles of beer on the wall, 75 bottles of beer.
Take one down and pass it around, 74 bottles of beer on the wall.

74 bottles of beer on the wall, 74 bottles of beer.
Take one down and pass it around, 73 bottles of beer on the wall.

73 bottles of beer on the wall, 73 bottles of beer.
Take one down and pass it around, 72 bottles of beer on the wall.

72 bottles of beer on the wall, 72 bottles of beer.
Take one down and pass it around, 71 bottles of beer on the wall.

71 bottles of beer on the wall, 71 bottles of beer.
Take one down and pass it around, 70 bottles of beer on the wall.

70 bottles of beer on the wall, 70 bottles of beer.
Take one down and pass it around, 69 bottles of beer on the wall.

69 bottles of beer on the wall, 69 bottles of beer.
Take one down and pass it around, 68 bottles of beer on the wall.

68 bottles of beer on the wall, 68 bottles of beer.
Take one down and pass it around, 67 bottles of beer on the wall.

67 bottles of beer on the wall, 67 bottles of beer.
Take one down and pass it around, 66 bottles of beer on the wall.

66 bottles of beer on the wall, 66 bottles of beer.
Take one down and pass it around, 65 bottles of beer on the wall.

65 bottles of beer on the wall, 65 bottles of beer.
Take one down and pass it around, 64 bottles of beer on the wall.

64 bottles of beer on the wall, 64 bottles of beer.
Take one down and pass it around, 63 bottles of beer on the wall.

63 bottles of beer on the wall, 63 bottles of beer.
Take one down and pass it around, 62 bottles of beer on the wall.

62 bottles of beer on the wall, 62 bottles of beer.
Take one down and pass it around, 61 bottles of beer on the wall.

61 bottles of beer on the wall, 61 bottles of beer.
Take one down and pass it around, 60 bottles of beer on the wall.

60 bottles of beer on the wall, 60 bottles of beer.
Take one down and pass it around, 59 bottles of beer on the wall.

59 bottles of beer on the wall, 59 bottles of beer.
Take one down and pass it around, 58 bottles of beer on the wall.

58 bottles of beer on the wall, 58 bottles of beer.
Take one down and pass it around, 57 bottles of beer on the wall.

57 bottles of beer on the wall, 57 bottles of beer.
Take one down and pass it around, 56 bottles of beer on the wall.

56 bottles of beer on the wall, 56 bottles of beer.
Take one down and pass it around, 55 bottles of beer on the wall.

55 bottles of beer on the wall, 55 bottles of beer.
Take one down and pass it around, 54 bottles of beer on the wall.

54 bottles of beer on the wall, 54 bottles of beer.
Take one down and pass it around, 53 bottles of beer on the wall.

53 bottles of beer on the wall, 53 bottles of beer.
Take one down and pass it around, 52 bottles of beer on the wall.

52 bottles of beer on the wall, 52 bottles of beer.
Take one down and pass it around, 51 bottles of beer on the wall.

51 bottles of beer on the wall, 51 bottles of beer.
Take one down and pass it around, 50 bottles of beer on the wall.

50 bottles of beer on the wall, 50 bottles of beer.
Take one down and pass it around, 49 bottles of beer on the wall.

49 bottles of beer on the wall, 49 bottles of beer.
Take one down and pass it around, 48 bottles of beer on the wall.

48 bottles of beer on the wall, 48 bottles of beer.
Take one down and pass it around, 47 bottles of beer on the wall.

47 bottles of beer on the wall, 47 bottles of beer.
Take one down and pass it around, 46 bottles of beer on the wall.

46 bottles of beer on the wall, 46 bottles of beer.
Take one down and pass it around, 45 bottles of beer on the wall.

45 bottles of beer on the wall, 45 bottles of beer.
Take one down and pass it around, 44 bottles of beer on the wall.

44 bottles of beer on the wall, 44 bottles of beer.
Take one down and pass it around, 43 bottles of beer on the wall.

43 bottles of beer on the wall, 43 bottles of beer.
Take one down and pass it around, 42 bottles of beer on the wall.

42 bottles of beer on the wall, 42 bottles of beer.
Take one down and pass it around, 41 bottles of beer on the wall.

41 bottles of beer on the wall, 41 bottles of beer.
Take one down and pass it around, 40 bottles of beer on the wall.

40 bottles of beer on the wall, 40 bottles of beer.
Take one down and pass it around, 39 bottles of beer on the wall.

39 bottles of beer on the wall, 39 bottles of beer.
Take one down and pass it around, 38 bottles of beer on the wall.

38 bottles of beer on the wall, 38 bottles of beer.
Take one down and pass it around, 37 bottles of beer on the wall.

37 bottles of beer on the wall, 37 bottles of beer.
Take one down and pass it around, 36 bottles of beer on the wall.

36 bottles of beer on the wall, 36 bottles of beer.
Take one down and pass it around, 35 bottles of beer on the wall.

35 bottles of beer on the wall, 35 bottles of beer.
Take one down and pass it around, 34 bottles of beer on the wall.

34 bottles of beer on the wall, 34 bottles of beer.
Take one down and pass it around, 33 bottles of beer on the wall.

33 bottles of beer on the wall, 33 bottles of beer.
Take one down and pass it around, 32 bottles of beer on the wall.

32 bottles of beer on the wall, 32 bottles of beer.
Take one down and pass it around, 31 bottles of beer on the wall.

31 bottles of beer on the wall, 31 bottles of beer.
Take one down and pass it around, 30 bottles of beer on the wall.

30 bottles of beer on the wall, 30 bottles of beer.
Take one down and pass it around, 29 bottles of beer on the wall.

29 bottles of beer on the wall, 29 bottles of beer.
Take one down and pass it around, 28 bottles of beer on the wall.

28 bottles of beer on the wall, 28 bottles of beer.
Take one down and pass it around, 27 bottles of beer on the wall.

27 bottles of beer on the wall, 27 bottles of beer.
Take one down and pass it around, 26 bottles of beer on the wall.

26 bottles of beer on the wall, 26 bottles of beer.
Take one down and pass it around, 25 bottles of beer on the wall.

25 bottles of beer on the wall, 25 bottles of beer.
Take one down and pass it around, 24 bottles of beer on the wall.

24 bottles of beer on the wall, 24 bottles of beer.
Take one down and pass it around, 23 bottles of beer on the wall.

23 bottles of beer on the wall, 23 bottles of beer.
Take one down and pass it around, 22 bottles of beer on the wall.

22 bottles of beer on the wall, 22 bottles of beer.
Take one down and pass it around, 21 bottles of beer on the wall.

21 bottles of beer on the wall, 21 bottles of beer.
Take one down and pass it around, 20 bottles of beer on the wall.

20 bottles of beer on the wall, 20 bottles of beer.
Take one down and pass it around, 19 bottles of beer on the wall.

19 bottles of beer on the wall, 19 bottles of beer.
Take one down and pass it around, 18 bottles of beer on the wall.

18 bottles of beer on the wall, 18 bottles of beer.
Take one down and pass it around, 17 bottles of beer on the wall.

17 bottles of beer on the wall, 17 bottles of beer.
Take one down and pass it around, 16 bottles of beer on the wall.

16 bottles of beer on the wall, 16 bottles of beer.
Take one down and pass it around, 15 bottles of beer on the wall.

15 bottles of beer on the wall, 15 bottles of beer.
Take one down and pass it around, 14 bottles of beer on the wall.

14 bottles of beer on the wall, 14 bottles of beer.
Take one down and pass it around, 13 bottles of beer on the wall.

13 bottles of beer on the wall, 13 bottles of beer.
Take one down and pass it around, 12 bottles of beer on the wall.

12 bottles of beer on the wall, 12 bottles of beer.
Take one down and pass it around, 11 bottles of beer on the wall.

11 bottles of beer on the wall, 11 bottles of beer.
Take one down and pass it around, 10 bottles of beer on the wall.

10 bottles of beer on the wall, 10 bottles of beer.
Take one down and pass it around, 9 bottles of beer on the wall.

9 bottles of beer on the wall, 9 bottles of beer.
Take one down and pass it around, 8 bottles of beer on the wall.

8 bottles of beer on the wall, 8 bottles of beer.
Take one down and pass it around, 7 bottles of beer on the wall.

7 bottles of beer on the wall, 7 bottles of beer.
Take one down and pass it around, 6 bottles of beer on the wall.

6 bottles of beer on the wall, 6 bottles of beer.
Take one down and pass it around, 5 bottles of beer on the wall.

5 bottles of beer on the wall, 5 bottles of beer.
Take one down and pass it around, 4 bottles of beer on the wall.

4 bottles of beer on the wall, 4 bottles of beer.
Take one down and pass it around, 3 bottles of beer on the wall.

3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Take it down and pass it around, no more bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
</code></pre>
<a class="header" href="#加分-1" id="加分-1"><h2>加分</h2></a>
<p>你是否通过了测试，并且代码干净了? 如果您愿意,可以尝试以下加分项:</p>
<ul>
<li>尽可能多地删除重复.</li>
<li>优化可读性,即使它意味着引入重复.</li>
<li>如果您删除了所有重复项,那么您是否有很多条件? 如果它适用于这种语言,请尝试用多态替换条件语句。它的可读性如何?</li>
</ul>
<p>那么请在提交的评论中，分享您的想法.这个实验是否让代码更好? 更差?你从中学到了什么?</p>
<a class="header" href="#source-6" id="source-6"><h2>Source</h2></a>
<p>Learn to Program by Chris Pine <a href="http://pine.fm/LearnToProgram/?Chapter=06">http://pine.fm/LearnToProgram/?Chapter=06</a></p>
<a class="header" href="#2-开始你的表演-7" id="2-开始你的表演-7"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn verse(n: i32) -&gt; String {
   unimplemented!(&quot;emit verse {}&quot;, n)
}

pub fn sing(start: i32, end: i32) -&gt; String {
   unimplemented!(&quot;sing verses {} to {}, inclusive&quot;, start, end)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-7" id="3-测试代码查看-7"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_verse_0() {
   assert_eq!(verse(0), &quot;No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n&quot;);
}

#[test]
//#[ignore]
fn test_verse_1() {
   assert_eq!(verse(1), &quot;1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n&quot;);
}

#[test]
//#[ignore]
fn test_verse_2() {
   assert_eq!(verse(2), &quot;2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n&quot;);
}

#[test]
//#[ignore]
fn test_verse_8() {
   assert_eq!(verse(8), &quot;8 bottles of beer on the wall, 8 bottles of beer.\nTake one down and pass it around, 7 bottles of beer on the wall.\n&quot;);
}

#[test]
//#[ignore]
fn test_song_8_6() {
   assert_eq!(sing(8, 6), &quot;8 bottles of beer on the wall, 8 bottles of beer.\nTake one down and pass it around, 7 bottles of beer on the wall.\n\n7 bottles of beer on the wall, 7 bottles of beer.\nTake one down and pass it around, 6 bottles of beer on the wall.\n\n6 bottles of beer on the wall, 6 bottles of beer.\nTake one down and pass it around, 5 bottles of beer on the wall.\n&quot;);
}

#[test]
//#[ignore]
fn test_song_3_0() {
   assert_eq!(sing(3, 0), &quot;3 bottles of beer on the wall, 3 bottles of beer.\nTake one down and pass it around, 2 bottles of beer on the wall.\n\n2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n\n1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n&quot;);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-7" id="4-答案-7"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn verse(n: i32) -&gt; String {
   match n {
       0 =&gt; &quot;No more bottles of beer on the wall, no more bottles of beer.\n\
             Go to the store and buy some more, 99 bottles of beer on the wall.\n&quot;
           .to_string(),
       1 =&gt; &quot;1 bottle of beer on the wall, 1 bottle of beer.\n\
             Take it down and pass it around, no more bottles of beer on the wall.\n&quot;
           .to_string(),
       2 =&gt; &quot;2 bottles of beer on the wall, 2 bottles of beer.\n\
             Take one down and pass it around, 1 bottle of beer on the wall.\n&quot;
           .to_string(),
       n if n &gt; 2 &amp;&amp; n &lt;= 99 =&gt; format!(
           &quot;{n} bottles of beer on the wall, {n} bottles of beer.\n\
            Take one down and pass it around, {n_minus_1} bottles of beer on the wall.\n&quot;,
           n = n,
           n_minus_1 = n - 1
       ),
       _ =&gt; panic!(),
   }
}

pub fn sing(start: i32, end: i32) -&gt; String {
   (end..start + 1)
       .rev()
       .map(|n| verse(n))
       .collect::&lt;Vec&lt;_&gt;&gt;()
       .join(&quot;\n&quot;)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-7" id="填充相关-7"><h2>填充/相关</h2></a>
<a class="header" href="#谚语串烧-proverb" id="谚语串烧-proverb"><h1>谚语串烧-Proverb</h1></a>
<a class="header" href="#1-readme-8" id="1-readme-8"><h2>1. Readme</h2></a>
<a class="header" href="#谚语" id="谚语"><h1>谚语</h1></a>
<p>因为没有马蹄钉,一个王国就消失了,或者俗话说.</p>
<p>给出一个输入列表,生成相关的谚语.例如,</p>
<ul>
<li>给定列表<code>[&quot;nail&quot;, &quot;shoe&quot;, &quot;horse&quot;, &quot;rider&quot;, &quot;message&quot;, &quot;battle&quot;, &quot;kingdom&quot;]</code></li>
<li>你将输出这个谚语的全文:</li>
</ul>
<pre><code class="language-text">For want of a nail the shoe was lost.
For want of a shoe the horse was lost.
For want of a horse the rider was lost.
For want of a rider the message was lost.
For want of a message the battle was lost.
For want of a battle the kingdom was lost.
And all for the want of a nail.
</code></pre>
<p>请注意,输入列表可能会有所不同; 您的解决方案应该能够处理<strong>任意长度和内容</strong>的列表。输出文本的行不应该是<strong>静态的、不变的</strong>字符串;
所有的都应该根据给定的输入而变化.</p>
<a class="header" href="#source-7" id="source-7"><h2>Source</h2></a>
<p>Wikipedia <a href="http://en.wikipedia.org/wiki/For_Want_of_a_Nail">http://en.wikipedia.org/wiki/For_Want_of_a_Nail</a></p>
<a class="header" href="#2-开始你的表演-8" id="2-开始你的表演-8"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn build_proverb(list: Vec&lt;&amp;str&gt;) -&gt; String {
   unimplemented!(&quot;build a proverb from this list of items: {:?}&quot;, list)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-8" id="3-测试代码查看-8"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_two_pieces() {
   let input = vec![&quot;nail&quot;, &quot;shoe&quot;];
   let expected = vec![
       &quot;For want of a nail the shoe was lost.&quot;,
       &quot;And all for the want of a nail.&quot;,
   ]
   .join(&quot;\n&quot;);
   assert_eq!(build_proverb(input), expected);
}

// Notice the change in the last line at three pieces.
#[test]
//#[ignore]
fn test_three_pieces() {
   let input = vec![&quot;nail&quot;, &quot;shoe&quot;, &quot;horse&quot;];
   let expected = vec![
       &quot;For want of a nail the shoe was lost.&quot;,
       &quot;For want of a shoe the horse was lost.&quot;,
       &quot;And all for the want of a nail.&quot;,
   ]
   .join(&quot;\n&quot;);
   assert_eq!(build_proverb(input), expected);
}

#[test]
//#[ignore]
fn test_one_piece() {
   let input = vec![&quot;nail&quot;];
   let expected = String::from(&quot;And all for the want of a nail.&quot;);
   assert_eq!(build_proverb(input), expected);
}

#[test]
//#[ignore]
fn test_zero_pieces() {
   let input: Vec&lt;&amp;str&gt; = vec![];
   let expected = String::new();
   assert_eq!(build_proverb(input), expected);
}

#[test]
//#[ignore]
fn test_full() {
   let input = vec![
       &quot;nail&quot;, &quot;shoe&quot;, &quot;horse&quot;, &quot;rider&quot;, &quot;message&quot;, &quot;battle&quot;, &quot;kingdom&quot;,
   ];
   let expected = vec![
       &quot;For want of a nail the shoe was lost.&quot;,
       &quot;For want of a shoe the horse was lost.&quot;,
       &quot;For want of a horse the rider was lost.&quot;,
       &quot;For want of a rider the message was lost.&quot;,
       &quot;For want of a message the battle was lost.&quot;,
       &quot;For want of a battle the kingdom was lost.&quot;,
       &quot;And all for the want of a nail.&quot;,
   ]
   .join(&quot;\n&quot;);
   assert_eq!(build_proverb(input), expected);
}

#[test]
//#[ignore]
fn test_three_pieces_modernized() {
   let input = vec![&quot;pin&quot;, &quot;gun&quot;, &quot;soldier&quot;, &quot;battle&quot;];
   let expected = vec![
       &quot;For want of a pin the gun was lost.&quot;,
       &quot;For want of a gun the soldier was lost.&quot;,
       &quot;For want of a soldier the battle was lost.&quot;,
       &quot;And all for the want of a pin.&quot;,
   ]
   .join(&quot;\n&quot;);
   assert_eq!(build_proverb(input), expected);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-8" id="4-答案-8"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn build_proverb(items: Vec&lt;&amp;str&gt;) -&gt; String {
   let mut stanzas = Vec::with_capacity(items.len());
   for index in 0..items.len() {
       if index == items.len() - 1 {
           stanzas.push(format!(&quot;And all for the want of a {}.&quot;, items[0]));
       } else {
           stanzas.push(format!(
               &quot;For want of a {} the {} was lost.&quot;,
               items[index],
               items[index + 1]
           ));
       }
   }
   stanzas.join(&quot;\n&quot;)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-8" id="填充相关-8"><h2>填充/相关</h2></a>
<a class="header" href="#平方差-difference-of-squares" id="平方差-difference-of-squares"><h1>平方差-Difference Of Squares</h1></a>
<a class="header" href="#1-readme-9" id="1-readme-9"><h2>1. Readme</h2></a>
<a class="header" href="#平方差" id="平方差"><h1>平方差</h1></a>
<p>求,前n个自然数的和平方，与，平方和,之间的差值.</p>
<p>例如:</p>
<p>前十个自然数之和的平方为:</p>
<ul>
<li><code>(1 + 2 + ... + 10)² = 55² = 3025.</code></li>
</ul>
<p>前十个自然数的平方和为:</p>
<ul>
<li><code>1² + 2² + ... + 10² = 385.</code></li>
</ul>
<p>因此,前十个自然数之和的平方,和,前十个自然数之和的平方之差是:</p>
<ul>
<li><code>3025 - 385 = 2640.</code></li>
</ul>
<a class="header" href="#source-8" id="source-8"><h2>Source</h2></a>
<p>Problem 6 at Project Euler <a href="http://projecteuler.net/problem=6">http://projecteuler.net/problem=6</a></p>
<a class="header" href="#2-开始你的表演-9" id="2-开始你的表演-9"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn square_of_sum(n: u32) -&gt; u32 {
   unimplemented!(&quot;square of sum of 1...{}&quot;, n)
}

pub fn sum_of_squares(n: u32) -&gt; u32 {
   unimplemented!(&quot;sum of squares of 1...{}&quot;, n)
}

pub fn difference(n: u32) -&gt; u32 {
   unimplemented!(
       &quot;difference between square of sum of 1...{n} and sum of squares of 1...{n}&quot;,
       n = n,
   )
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-9" id="3-测试代码查看-9"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_square_of_sum_1() {
   assert_eq!(1, square_of_sum(1));
}

#[test]
//#[ignore]
fn test_square_of_sum_5() {
   assert_eq!(225, square_of_sum(5));
}

#[test]
//#[ignore]
fn test_square_of_sum_100() {
   assert_eq!(25502500, square_of_sum(100));
}

#[test]
//#[ignore]
fn test_sum_of_squares_1() {
   assert_eq!(1, sum_of_squares(1));
}

#[test]
//#[ignore]
fn test_sum_of_squares_5() {
   assert_eq!(55, sum_of_squares(5));
}

#[test]
//#[ignore]
fn test_sum_of_squares_100() {
   assert_eq!(338350, sum_of_squares(100));
}

#[test]
//#[ignore]
fn test_difference_1() {
   assert_eq!(0, difference(1));
}

#[test]
//#[ignore]
fn test_difference_5() {
   assert_eq!(170, difference(5));
}

#[test]
//#[ignore]
fn test_difference_100() {
   assert_eq!(25164150, difference(100));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-9" id="4-答案-9"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn square_of_sum(n: u32) -&gt; u32 {
   let sum = n * (n + 1) / 2;
   sum * sum
}

pub fn sum_of_squares(n: u32) -&gt; u32 {
   (0..n + 1).map(|x| x * x).fold(0, |accum, x| accum + x)
}

pub fn difference(n: u32) -&gt; u32 {
   square_of_sum(n) - sum_of_squares(n)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-9" id="填充相关-9"><h2>填充/相关</h2></a>
<a class="header" href="#sum-of-multiples" id="sum-of-multiples"><h1>Sum Of Multiples</h1></a>
<a class="header" href="#1-readme-10" id="1-readme-10"><h2>1. Readme</h2></a>
<a class="header" href="#倍数之和" id="倍数之和"><h1>倍数之和</h1></a>
<p>给定一个<strong>数字</strong>,找出<strong>另外的特定数字</strong>的所有唯一倍数的总和,但不包括第一个数字.</p>
<p>如果我们列出<strong>20</strong>以下，<strong>3或5</strong>的倍数的所有自然数,我们得到<strong>3,5,6,9,10,12,15和18</strong>.</p>
<p>这些倍数的总和是<strong>78</strong>.</p>
<a class="header" href="#资源-1" id="资源-1"><h2>资源</h2></a>
<p>在项目Euler中，问题1的变种<a href="http://projecteuler.net/problem=1">http://projecteuler.net/problem=1</a></p>
<a class="header" href="#2-开始你的表演-10" id="2-开始你的表演-10"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn sum_of_multiples(limit: u32, factors: &amp;[u32]) -&gt; u32 {
   unimplemented!(
       &quot;Sum the multiples of all of {:?} which are less than {}&quot;,
       factors,
       limit
   )
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-10" id="3-测试代码查看-10"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn multiples_one() {
   assert_eq!(0, sum_of_multiples(1, &amp;[3, 5]))
}

#[test]
//#[ignore]
fn multiples_two() {
   assert_eq!(3, sum_of_multiples(4, &amp;[3, 5]))
}

#[test]
//#[ignore]
fn multiples_three() {
   assert_eq!(23, sum_of_multiples(10, &amp;[3, 5]))
}

#[test]
//#[ignore]
fn multiples_four() {
   assert_eq!(2318, sum_of_multiples(100, &amp;[3, 5]))
}

#[test]
//#[ignore]
fn multiples_five() {
   assert_eq!(233168, sum_of_multiples(1000, &amp;[3, 5]))
}

#[test]
//#[ignore]
fn multiples_six() {
   assert_eq!(51, sum_of_multiples(20, &amp;[7, 13, 17]))
}

#[test]
//#[ignore]
fn multiples_seven() {
   assert_eq!(30, sum_of_multiples(15, &amp;[4, 6]))
}

#[test]
//#[ignore]
fn multiples_eight() {
   assert_eq!(4419, sum_of_multiples(150, &amp;[5, 6, 8]))
}

#[test]
//#[ignore]
fn multiples_nine() {
   assert_eq!(275, sum_of_multiples(51, &amp;[5, 25]))
}

#[test]
//#[ignore]
fn multiples_ten() {
   assert_eq!(2203160, sum_of_multiples(10000, &amp;[43, 47]))
}

#[test]
//#[ignore]
fn multiples_eleven() {
   assert_eq!(4950, sum_of_multiples(100, &amp;[1]))
}

#[test]
//#[ignore]
fn multiples_twelve() {
   assert_eq!(0, sum_of_multiples(10000, &amp;[]))
}

#}</code></pre></pre>
<a class="header" href="#4-答案-10" id="4-答案-10"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::BTreeSet;

pub fn sum_of_multiples(limit: u32, factors: &amp;[u32]) -&gt; u32 {
   let mut multiples: BTreeSet&lt;u32&gt; = BTreeSet::new();

   for &amp;f in factors {
       let mut multiplier = 2;
       let mut x = f;
       while x &lt; limit {
           multiples.insert(x);
           x = f * multiplier;
           multiplier += 1;
       }
   }

   multiples.iter().sum()
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-10" id="填充相关-10"><h2>填充/相关</h2></a>
<a class="header" href="#grains" id="grains"><h1>Grains</h1></a>
<a class="header" href="#1-readme-11" id="1-readme-11"><h2>1. Readme</h2></a>
<a class="header" href="#谷物" id="谷物"><h1>谷物</h1></a>
<p>计算棋盘上的小麦粒数,假设每个方格的数量增加一倍.</p>
<p>曾经有一位睿智的仆人拯救了王子的生命。国王承诺支付仆人梦寐以求的一切。知道国王喜欢国际象棋,仆人告诉国王他想吃小麦粒，在棋盘的第一个正方形上放一粒小麦。而接下来的方格是两粒.四粒小麦放在第三格,依此类推.</p>
<p>棋盘上有 64 个方格.</p>
<p>编写代码，用来显示:</p>
<ul>
<li>每个方格上有多少谷物,和</li>
<li>谷物总数</li>
</ul>
<a class="header" href="#加分-2" id="加分-2"><h2>加分</h2></a>
<p>你是否通过了测试，并且代码干净了? 如果您愿意,可以尝试以下一些额外的事情:</p>
<ul>
<li>优化速度.</li>
<li>优化可读性.</li>
</ul>
<p>那么请在提交的评论中分享您的想法.这个实验是否使代码更好? 更差? 你从中学到了什么吗?</p>
<a class="header" href="#资源-2" id="资源-2"><h2>资源</h2></a>
<p>JavaRanch Cattle 驱动,练习 6 <a href="http://www.javaranch.com/grains.jsp">http://www.javaranch.com/grains.jsp</a></p>
<a class="header" href="#2-开始你的表演-11" id="2-开始你的表演-11"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn square(s: u32) -&gt; u64 {
   unimplemented!(&quot;grains of rice on square {}&quot;, s);
}

pub fn total() -&gt; u64 {
   unimplemented!();
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-11" id="3-测试代码查看-11"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn square_one() {
   assert_eq!(square(1), 1);
}

#[test]
//#[ignore]
fn square_two() {
   assert_eq!(square(2), 2);
}

#[test]
//#[ignore]
fn square_three() {
   assert_eq!(square(3), 4);
}

#[test]
//#[ignore]
fn square_four() {
   assert_eq!(square(4), 8);
}

#[test]
//#[ignore]
fn square_sixteen() {
   assert_eq!(square(16), 32_768);
}

#[test]
//#[ignore]
fn square_thirty_two() {
   assert_eq!(square(32), 2_147_483_648);
}

#[test]
//#[ignore]
fn square_sixty_four() {
   assert_eq!(square(64), 9_223_372_036_854_775_808);
}

#[test]
//#[ignore]
#[should_panic(expected = &quot;Square must be between 1 and 64&quot;)]
fn square_zero_panics() {
   square(0);
}

#[test]
//#[ignore]
#[should_panic(expected = &quot;Square must be between 1 and 64&quot;)]
fn square_sixty_five_panics() {
   square(65);
}

#[test]
//#[ignore]
fn total_sums_all_squares() {
   assert_eq!(total(), 18_446_744_073_709_551_615);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-11" id="4-答案-11"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn square(s: u32) -&gt; u64 {
   if s == 0 || s &gt; 64 {
       panic!(&quot;Square must be between 1 and 64&quot;);
   }

   2u64.pow(s - 1)
}

pub fn total() -&gt; u64 {
   (1..65).fold(0, |acc, s| acc + square(s))
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-11" id="填充相关-11"><h2>填充/相关</h2></a>
<a class="header" href="#pythagorean-triplet" id="pythagorean-triplet"><h1>Pythagorean Triplet</h1></a>
<a class="header" href="#1-readme-12" id="1-readme-12"><h2>1. Readme</h2></a>
<a class="header" href="#勾股数" id="勾股数"><h1>勾股数</h1></a>
<p>勾股数是一组,三个自然数,{a,b,c}, 如</p>
<pre><code class="language-text">a**2 + b**2 = c**2
</code></pre>
<p>这样,</p>
<pre><code class="language-text">a &lt; b &lt; c
</code></pre>
<p>例如,</p>
<pre><code class="language-text">3**2 + 4**2 = 9 + 16 = 25 = 5**2.
</code></pre>
<p>问: 请找出 <strong>a，b，c</strong>，恰好符合勾股定理, 而其中 a+b+c=1000.</p>
<p>返回， <code>a * b * c</code> 值.</p>
<a class="header" href="#资源-3" id="资源-3"><h2>资源</h2></a>
<p>欧拉项目,问题 9<a href="http://projecteuler.net/problem=9">http://projecteuler.net/problem=9</a></p>
<a class="header" href="#2-开始你的表演-12" id="2-开始你的表演-12"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn find() -&gt; Option&lt;u32&gt; {
   unimplemented!();
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-12" id="3-测试代码查看-12"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_answer() {
   assert_eq!(find(), Some(31875000));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-12" id="4-答案-12"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn find() -&gt; Option&lt;u32&gt; {
   for a in 1..1000 {
       for b in (a + 1)..(1000 - a) {
           let c = 1000 - (a + b);
           if a * a + b * b == c * c {
               return Some(a * b * c);
           }
       }
   }
   None
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-12" id="填充相关-12"><h2>填充/相关</h2></a>
<a class="header" href="#prime-factors" id="prime-factors"><h1>Prime Factors</h1></a>
<a class="header" href="#1-readme-13" id="1-readme-13"><h2>1. Readme</h2></a>
<a class="header" href="#素数因子" id="素数因子"><h1>素数因子</h1></a>
<p>计算给定自然数的素因子.</p>
<p>质数(素数): 只能被自身和 1 整除.</p>
<p>注意,1 不是素数.</p>
<a class="header" href="#例子" id="例子"><h2>例子</h2></a>
<p>60 的主要因素是什么?</p>
<ul>
<li>我们的第一个除数是 2 。 2 被除以 60,剩下 30。</li>
<li>2 被除以 30,剩下 15。
<ul>
<li>2 不能被除以 15。让我们转到下一个除数,3.</li>
</ul>
</li>
<li>3 被除以 15 分,5 剩下。
<ul>
<li>3 不能被除以 5。下一个可能的因素是 4.</li>
<li>4 不能被除以 5。下一个可能的因素是 5.</li>
</ul>
</li>
<li>5 确实能被除以 5.</li>
<li>我们只剩下 1 ,所以现在,我们完成了。</li>
</ul>
<p>我们在该计算中成功, 而 <strong>60</strong>除数代表 ∶ <code>2, 2, 3 和 5</code> 为主要因子的列表.</p>
<p>你可以自己检查一下:</p>
<ul>
<li>2 × 2 × 3 × 5</li>
<li>= 4 × 15</li>
<li>= 60</li>
<li>成功!</li>
</ul>
<a class="header" href="#资源-4" id="资源-4"><h2>资源</h2></a>
<p>Uncle Bob 的主要因素算法<a href="http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata">http://butunclebob.com/ArticleS.UncleBob.ThePrimeFactorsKata</a></p>
<a class="header" href="#2-开始你的表演-13" id="2-开始你的表演-13"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn factors(n: u64) -&gt; Vec&lt;u64&gt; {
   unimplemented!(&quot;This should calculate the prime factors of {}&quot;, n)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-13" id="3-测试代码查看-13"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_no_factors() {
   assert_eq!(factors(1), vec![]);
}

#[test]
//#[ignore]
fn test_prime_number() {
   assert_eq!(factors(2), vec![2]);
}

#[test]
//#[ignore]
fn test_square_of_a_prime() {
   assert_eq!(factors(9), vec![3, 3]);
}

#[test]
//#[ignore]
fn test_cube_of_a_prime() {
   assert_eq!(factors(8), vec![2, 2, 2]);
}

#[test]
//#[ignore]
fn test_product_of_primes_and_non_primes() {
   assert_eq!(factors(12), vec![2, 2, 3]);
}

#[test]
//#[ignore]
fn test_product_of_primes() {
   assert_eq!(factors(901255), vec![5, 17, 23, 461]);
}

#[test]
//#[ignore]
fn test_factors_include_large_prime() {
   assert_eq!(factors(93819012551), vec![11, 9539, 894119]);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-13" id="4-答案-13"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn factors(n: u64) -&gt; Vec&lt;u64&gt; {
   let mut val = n;
   let mut out: Vec&lt;u64&gt; = vec![];
   let mut possible: u64 = 2;
   while val &gt; 1 {
       while val % possible == 0 {
           out.push(possible);
           val /= possible;
       }
       possible += 1;
   }
   out
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-13" id="填充相关-13"><h2>填充/相关</h2></a>
<a class="header" href="#series" id="series"><h1>Series</h1></a>
<a class="header" href="#1-readme-14" id="1-readme-14"><h2>1. Readme</h2></a>
<a class="header" href="#系列" id="系列"><h1>系列</h1></a>
<p>给定一串数字,输出所有连续的<code>n</code>长度顺序子串。</p>
<p>例如,字符串”49142”长度为<code>3</code>的子串系列:</p>
<ul>
<li>“491”</li>
<li>“914”</li>
<li>“142”</li>
</ul>
<p>以下长度为 <code>4</code> 的 系列:</p>
<ul>
<li>“4914”</li>
<li>“9142”</li>
</ul>
<p>如果你要求一个 5 位数字，长度为 6 的系列,你应该得到原数字。</p>
<p>请注意,这些系列只需要在输入中是<em>相邻的位置</em>; 数字不需要在<em>数字上连续</em>.</p>
<a class="header" href="#资源-5" id="资源-5"><h2>资源</h2></a>
<p>Project Euler 中，问题 8 的一个子集<a href="http://projecteuler.net/problem=8">http://projecteuler.net/problem=8</a></p>
<a class="header" href="#2-开始你的表演-14" id="2-开始你的表演-14"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn series(digits: &amp;str, len: usize) -&gt; Vec&lt;String&gt; {
   unimplemented!(
       &quot;What are the series of length {} in string {:?}&quot;,
       len,
       digits
   )
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-14" id="3-测试代码查看-14"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_with_zero_length() {
   let expected = vec![&quot;&quot;.to_string(); 6];
   assert_eq!(series(&quot;92017&quot;, 0), expected);
}

#[test]
//#[ignore]
fn test_with_length_2() {
   let expected = vec![
       &quot;92&quot;.to_string(),
       &quot;20&quot;.to_string(),
       &quot;01&quot;.to_string(),
       &quot;17&quot;.to_string(),
   ];
   assert_eq!(series(&quot;92017&quot;, 2), expected);
}

#[test]
//#[ignore]
fn test_with_numbers_length() {
   let expected = vec![&quot;92017&quot;.to_string()];
   assert_eq!(series(&quot;92017&quot;, 5), expected);
}

#[test]
//#[ignore]
fn test_too_long() {
   let expected: Vec&lt;String&gt; = vec![];
   assert_eq!(series(&quot;92017&quot;, 6), expected);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-14" id="4-答案-14"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn series(digits: &amp;str, len: usize) -&gt; Vec&lt;String&gt; {
   match len {
       0 =&gt; vec![&quot;&quot;.to_string(); digits.len() + 1],
       _ =&gt; digits
           .chars()
           .collect::&lt;Vec&lt;char&gt;&gt;()
           .windows(len)
           .map(|window| window.into_iter().collect::&lt;String&gt;())
           .collect::&lt;Vec&lt;String&gt;&gt;(),
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-14" id="填充相关-14"><h2>填充/相关</h2></a>
<a class="header" href="#armstrong-numbers" id="armstrong-numbers"><h1>Armstrong Numbers</h1></a>
<a class="header" href="#1-readme-15" id="1-readme-15"><h2>1. Readme</h2></a>
<a class="header" href="#水仙花数" id="水仙花数"><h1>水仙花数</h1></a>
<p>一个<a href="https://en.wikipedia.org/wiki/Narcissistic_number">Armstrong number</a>是一个数字,它是自身每个单数字与数字量的幂，之和。</p>
<p>例如:</p>
<ul>
<li>9 是水仙花数,因为<code>9 = 9^1 = 9</code></li>
<li>10 <em>不是</em>一个水仙花数,因为<code>10 != 1^2 + 0^2 = 1</code></li>
<li>153 是水仙花数,因为:<code>153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153</code></li>
<li>154 <em>不是</em>一个水仙花数,因为:<code>154 != 1^3 + 5^3 + 4^3 = 1 + 125 + 64 = 190</code></li>
</ul>
<p>写一些代码来确定一个数字是否水仙花数.</p>
<a class="header" href="#资源-6" id="资源-6"><h2>资源</h2></a>
<p>维基百科<a href="https://en.wikipedia.org/wiki/Narcissistic_number">https://en.wikipedia.org/wiki/Narcissistic_number</a></p>
<a class="header" href="#2-开始你的表演-15" id="2-开始你的表演-15"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn is_armstrong_number(num: u32) -&gt; bool {
   unimplemented!(&quot;true if {} is an armstrong number&quot;, num)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-15" id="3-测试代码查看-15"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_single_digit_numbers_are_armstrong_numbers() {
   assert!(is_armstrong_number(5))
}

#[test]
//#[ignore]
fn test_there_are_no_2_digit_armstrong_numbers() {
   assert!(!is_armstrong_number(10))
}

#[test]
//#[ignore]
fn test_three_digit_armstrong_number() {
   assert!(is_armstrong_number(153))
}

#[test]
//#[ignore]
fn test_three_digit_non_armstrong_number() {
   assert!(!is_armstrong_number(100))
}

#[test]
//#[ignore]
fn test_four_digit_armstrong_number() {
   assert!(is_armstrong_number(9474))
}

#[test]
//#[ignore]
fn test_four_digit_non_armstrong_number() {
   assert!(!is_armstrong_number(9475))
}

#[test]
//#[ignore]
fn test_seven_digit_armstrong_number() {
   assert!(is_armstrong_number(9926315))
}

#[test]
//#[ignore]
fn test_seven_digit_non_armstrong_number() {
   assert!(!is_armstrong_number(9926316))
}

#}</code></pre></pre>
<a class="header" href="#4-答案-15" id="4-答案-15"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn is_armstrong_number(num: u32) -&gt; bool {
   let s = format!(&quot;{}&quot;, num);
   let l = s.len();
   s.chars()
       .map(|c| c.to_digit(10).unwrap().pow(l as u32))
       .sum::&lt;u32&gt;() == num
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-15" id="填充相关-15"><h2>填充/相关</h2></a>
<a class="header" href="#collatz-conjecture" id="collatz-conjecture"><h1>Collatz Conjecture</h1></a>
<a class="header" href="#1-readme-16" id="1-readme-16"><h2>1. Readme</h2></a>
<a class="header" href="#考拉兹猜想" id="考拉兹猜想"><h1>考拉兹猜想</h1></a>
<p>在 考拉兹猜想 或 3n+1 猜想 可以如下:</p>
<p>是指对于每一个正整数，如果它是奇数，则对它乘 3 再加 1，如果它是偶数，则对它除以 2，如此循环，最终都能够得到 1。</p>
<p>给予一个数字<code>n</code>，那它到达 1 的步骤.</p>
<a class="header" href="#例子-1" id="例子-1"><h2>例子</h2></a>
<p>如 <code>n = 12</code>,步骤如下:将</p>
<ol start="0">
<li>12</li>
<li>6</li>
<li>3</li>
<li>10</li>
<li>5</li>
<li>16</li>
<li>8</li>
<li>4</li>
<li>2</li>
<li>1</li>
</ol>
<p>9 步骤。系统的输入是<code>n = 12</code>,返回值将是<code>9</code></p>
<a class="header" href="#资源-7" id="资源-7"><h2>资源</h2></a>
<p>以数学家 Lothar Collatz 命名的一个未解决的数学问题<a href="https://en.wikipedia.org/wiki/3x_%2B_1_problem">https://en.wikipedia.org/wiki/3x_%2B_1_problem</a></p>
<a class="header" href="#2-开始你的表演-16" id="2-开始你的表演-16"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn collatz(n: u64) -&gt; Option&lt;u64&gt; {
   unimplemented!(
       &quot;return Some(x) where x is the number of steps required to reach 1 starting with {}&quot;,
       n,
   )
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-16" id="3-测试代码查看-16"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_1() {
   assert_eq!(Some(0), collatz(1));
}

#[test]
//#[ignore]
fn test_16() {
   assert_eq!(Some(4), collatz(16));
}

#[test]
//#[ignore]
fn test_12() {
   assert_eq!(Some(9), collatz(12));
}

#[test]
//#[ignore]
fn test_1000000() {
   assert_eq!(Some(152), collatz(1000000));
}

#[test]
//#[ignore]
fn test_0() {
   assert_eq!(None, collatz(0));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-16" id="4-答案-16"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn collatz_positive(n: u64) -&gt; u64 {
   if n == 1 {
       0
   } else {
       1 + match n % 2 {
           0 =&gt; collatz_positive(n / 2),
           _ =&gt; collatz_positive(n * 3 + 1),
       }
   }
}

// return Ok(x) where x is the number of steps required to reach 1
pub fn collatz(n: u64) -&gt; Option&lt;u64&gt; {
   if n &lt; 1 {
       None
   } else {
       Some(collatz_positive(n))
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-16" id="填充相关-16"><h2>填充/相关</h2></a>
<a class="header" href="#diffie-hellman" id="diffie-hellman"><h1>Diffie Hellman</h1></a>
<a class="header" href="#1-readme-17" id="1-readme-17"><h2>1. Readme</h2></a>
<a class="header" href="#迪菲-赫尔曼" id="迪菲-赫尔曼"><h1>迪菲-赫尔曼</h1></a>
<p>迪菲-赫尔曼密钥交换</p>
<p>Alice 和 Bob 使用 迪菲-赫尔曼密钥来共享秘密。它们以素数开头,选择私钥,生成和共享公钥,然后生成共享密钥.</p>
<a class="header" href="#第-0-步" id="第-0-步"><h2>第 0 步</h2></a>
<p>测试程序提供素数 <code>p 和 g</code>.</p>
<a class="header" href="#步骤-1" id="步骤-1"><h2>步骤 1</h2></a>
<p>Alice 选择一个大于 1 ，且小于 p 的私钥。鲍勃做同样的事情来选择私钥 b.</p>
<a class="header" href="#第-2-步" id="第-2-步"><h2>第 2 步</h2></a>
<p>Alice 计算公钥 A.</p>
<pre><code>A = g**a mod p
</code></pre>
<p>使用相同的 p 和 g, Bob 类似地从他的私钥 b 计算公钥 B.</p>
<a class="header" href="#第-3-步" id="第-3-步"><h2>第 3 步</h2></a>
<p>Alice 和 Bob 交换公钥.Alice 计算密钥 s.</p>
<pre><code>s = B**a mod p
</code></pre>
<p>鲍勃计算</p>
<pre><code>s = A**b mod p
</code></pre>
<p>计算产生相同的结果! 爱丽丝和鲍勃现在分享秘密.</p>
<p>本练习的一种可能解决方案是实现您自己的模幂运算函数。要了解更多信息,请参阅<a href="https://en.wikipedia.org/wiki/Modular_exponentiation">following page</a>.</p>
<a class="header" href="#资源-8" id="资源-8"><h2>资源</h2></a>
<ul>
<li>
<p>维基百科,来自 www.cryptopp.com/wiki 的 1024 位密钥.<a href="http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange">http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange</a></p>
</li>
<li>
<p><a href="https://zh.wikipedia.org/wiki/%E8%BF%AA%E8%8F%B2-%E8%B5%AB%E7%88%BE%E6%9B%BC%E5%AF%86%E9%91%B0%E4%BA%A4%E6%8F%9B">中文维基</a></p>
</li>
</ul>
<a class="header" href="#2-开始你的表演-17" id="2-开始你的表演-17"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn private_key(p: u64) -&gt; u64 {
   unimplemented!(&quot;Pick a private key greater than 1 and less than {}&quot;, p)
}

pub fn public_key(p: u64, g: u64, a: u64) -&gt; u64 {
   unimplemented!(
       &quot;Calculate public key using prime numbers {} and {}, and private key {}&quot;,
       p,
       g,
       a
   )
}

pub fn secret(p: u64, b_pub: u64, a: u64) -&gt; u64 {
   unimplemented!(
       &quot;Calculate secret key using prime number {}, public key {}, and private key {}&quot;,
       p,
       b_pub,
       a
   )
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-17" id="3-测试代码查看-17"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_private_key_in_range_key() {
   let primes: Vec&lt;u64&gt; = vec![
       5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 773, 967, 3461, 6131,
   ];
   let private_keys: Vec&lt;u64&gt; = primes.iter().map(|x| private_key(*x)).collect();

   for i in 0..primes.len() {
       assert!(1 &lt; private_keys[i] &amp;&amp; private_keys[i] &lt; primes[i]);
   }
}

#[test]
//#[ignore]
fn test_public_key_correct() {
   let p: u64 = 23;
   let g: u64 = 5;

   let private_key: u64 = 6;
   let expected: u64 = 8;

   assert_eq!(public_key(p, g, private_key), expected);
}

#[test]
//#[ignore]
fn test_secret_key_correct() {
   let p: u64 = 11;

   let private_key_a = 7;
   let public_key_b = 8;
   let secret = secret(p, public_key_b, private_key_a);
   let expected = 2;

   assert_eq!(secret, expected);
}

#[test]
//#[ignore]
fn test_public_key_correct_big_numbers() {
   let p: u64 = 4_294_967_299;

   let g: u64 = 8;

   let private_key: u64 = 4_294_967_296;

   let expected: u64 = 4096;

   assert_eq!(public_key(p, g, private_key), expected);
}

#[test]
//#[ignore]
fn test_secret_key_correct_big_numbers() {
   let p: u64 = 4_294_967_927;

   let private_key_a = 4_294_967_300;

   let public_key_b = 843;

   let secret = secret(p, public_key_b, private_key_a);

   let expected = 1_389_354_282;

   assert_eq!(secret, expected);
}

#[test]
//#[ignore]
fn test_changed_secret_key() {
   let p: u64 = 13;
   let g: u64 = 11;

   let private_key_a = private_key(p);
   let private_key_b = private_key(p);

   let public_key_a = public_key(p, g, private_key_a);
   let public_key_b = public_key(p, g, private_key_b);

   // Key exchange
   let secret_a = secret(p, public_key_b, private_key_a);
   let secret_b = secret(p, public_key_a, private_key_b);

   assert_eq!(secret_a, secret_b);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-17" id="4-答案-17"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
extern crate rand;
use rand::{thread_rng, Rng};


/// Right-to-left modular exponentiation implementation
/// For more information see https://en.wikipedia.org/wiki/Modular_exponentiation
fn modular_exponentiation(base: u64, exponent: u64, modulus: u64) -&gt; u64 {
   let mut result = 1;

   let mut e = exponent;

   let mut b = base;

   while e &gt; 0 {
       if (e &amp; 1) == 1 {
           result = (result * b) % modulus;
       }

       e &gt;&gt;= 1;

       b = (b * b) % modulus;
   }

   result
}

pub fn private_key(p: u64) -&gt; u64 {
   let mut rng = thread_rng();
   rng.gen_range(2, p)
}

pub fn public_key(p: u64, g: u64, a: u64) -&gt; u64 {
   modular_exponentiation(g, a, p)
}

pub fn secret(p: u64, b_pub: u64, a: u64) -&gt; u64 {
   modular_exponentiation(b_pub, a, p)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-17" id="填充相关-17"><h2>填充/相关</h2></a>
<a class="header" href="#中等" id="中等"><h1>中等</h1></a>
<ul>
<li><a href="./saddle-points/README.zh.html">Saddle Points</a></li>
<li><a href="./isogram/README.zh.html">Isogram</a></li>
<li><a href="./say/README.zh.html">Say</a></li>
<li><a href="./run-length-encoding/README.zh.html">Run Length Encoding</a></li>
<li><a href="./isbn-verifier/README.zh.html">ISBN Verifier</a></li>
<li><a href="./perfect-numbers/README.zh.html">Perfect Numbers</a></li>
<li><a href="./clock/README.zh.html">Clock</a></li>
<li><a href="./dot-dsl/README.zh.html">DOT DSL</a></li>
<li><a href="./hamming/README.zh.html">Hamming</a></li>
<li><a href="./simple-linked-list/README.zh.html">Simple Linked List</a></li>
<li><a href="./pascal-s-triangle/README.zh.html">Pascal’s Triangle</a></li>
<li><a href="./scrabble-score/README.zh.html">Scrabble Score</a></li>
<li><a href="./pangram/README.zh.html">Pangram</a></li>
<li><a href="./paasio/README.zh.html">Paasio</a></li>
<li><a href="./nucleotide-count/README.zh.html">Nucleotide Count</a></li>
<li><a href="./luhn/README.zh.html">Luhn</a></li>
<li><a href="./largest-series-product/README.zh.html">Largest Series Product</a></li>
<li><a href="./word-count/README.zh.html">Word Count</a></li>
<li><a href="./atbash-cipher/README.zh.html">Atbash Cipher</a></li>
<li><a href="./crypto-square/README.zh.html">Crypto Square</a></li>
<li><a href="./rotational-cipher/README.zh.html">Rotational Cipher</a></li>
<li><a href="./simple-cipher/README.zh.html">Simple Cipher</a></li>
<li><a href="./rail-fence-cipher/README.zh.html">Rail Fence Cipher</a></li>
<li><a href="./etl/README.zh.html">ETL</a></li>
<li><a href="./accumulate/README.zh.html">Accumulate</a></li>
<li><a href="./acronym/README.zh.html">Acronym</a></li>
<li><a href="./sieve/README.zh.html">Sieve</a></li>
<li><a href="./rna-transcription/README.zh.html">RNA Transcription</a></li>
<li><a href="./triangle/README.zh.html">Triangle</a></li>
<li><a href="./roman-numerals/README.zh.html">Roman Numerals</a></li>
<li><a href="./all-your-base/README.zh.html">All Your Base</a></li>
<li><a href="./grade-school/README.zh.html">Grade School</a></li>
<li><a href="./binary-search/README.zh.html">Binary Search</a></li>
<li><a href="./robot-simulator/README.zh.html">Robot Simulator</a></li>
<li><a href="./bracket-push/README.zh.html">Bracket Push</a></li>
<li><a href="./luhn-from/README.zh.html">Luhn From</a></li>
<li><a href="./queen-attack/README.zh.html">Queen Attack</a></li>
<li><a href="./bowling/README.zh.html">Bowling</a></li>
<li><a href="./sublist/README.zh.html">Sublist</a></li>
<li><a href="./space-age/README.zh.html">Space Age</a></li>
<li><a href="./luhn-trait/README.zh.html">Luhn Trait</a></li>
<li><a href="./macros/README.zh.html">Macros</a></li>
<li><a href="./allergies/README.zh.html">Allergies</a></li>
<li><a href="./variable-length-quantity/README.zh.html">Variable Length Quantity</a></li>
<li><a href="./phone-number/README.zh.html">Phone Number</a></li>
<li><a href="./wordy/README.zh.html">Wordy</a></li>
<li><a href="./tournament/README.zh.html">Tournament</a></li>
<li><a href="./custom-set/README.zh.html">Custom Set</a></li>
<li><a href="./alphametics/README.zh.html">Alphametics</a></li>
<li><a href="./two-bucket/README.zh.html">Two Bucket</a></li>
<li><a href="./pig-latin/README.zh.html">Pig Latin</a></li>
<li><a href="./diamond/README.zh.html">Diamond</a></li>
<li><a href="./spiral-matrix/README.zh.html">Spiral Matrix</a></li>
<li><a href="./palindrome-products/README.zh.html">Palindrome Products</a></li>
<li><a href="./poker/README.zh.html">Poker</a></li>
<li><a href="./grep/README.zh.html">Grep</a></li>
<li><a href="./scale-generator/README.zh.html">Scale Generator</a></li>
<li><a href="./decimal/README.zh.html">Decimal</a></li>
<li><a href="./anagram/README.zh.html">Anagram</a></li>
<li><a href="./protein-translation/README.zh.html">Protein Translation</a></li>
<li><a href="./robot-name/README.zh.html">Robot Name</a></li>
</ul>
<a class="header" href="#saddle-points" id="saddle-points"><h1>Saddle Points</h1></a>
<a class="header" href="#1-readme-18" id="1-readme-18"><h2>1. Readme</h2></a>
<a class="header" href="#鞍点" id="鞍点"><h1>鞍点</h1></a>
<p>检测矩阵中的鞍点(saddle point).</p>
<p>所以说你有一个像这样的矩阵:</p>
<pre><code class="language-text">    0  1  2
  |---------
0 | 9  8  7
1 | 5  3  2     &lt;--- saddle point at (1,0)
2 | 6  6  7
</code></pre>
<p>它在(1,0)处有一个鞍点.</p>
<p>它被称为”鞍点”,因为它是该 <strong>行</strong> 最大数,也是该 <strong>列</strong> 的最小数。</p>
<p>矩阵可以具有零个或多个鞍点.</p>
<p>您的代码应该能够为任何给定矩阵提供所有鞍点的(可能为空)列表。</p>
<p>矩阵可以具有不同数量的行和列(非正方形)。</p>
<p>请注意,您可能会在线找到矩阵鞍点的其他定义,但本练习的测试遵循上述明确的定义.</p>
<a class="header" href="#资源-9" id="资源-9"><h2>资源</h2></a>
<p>J Dalbey 的编程实践问题<a href="http://users.csc.calpoly.edu/%7Ejdalbey/103/Projects/ProgrammingPractice.html">http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html</a></p>
<a class="header" href="#2-开始你的表演-18" id="2-开始你的表演-18"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn find_saddle_points(input: &amp;[Vec&lt;u64&gt;]) -&gt; Vec&lt;(usize, usize)&gt; {
   unimplemented!(
       &quot;find the saddle points of the following matrix: {:?}&quot;,
       input
   )
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-18" id="3-测试代码查看-18"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// We don't care about order
fn find_sorted_saddle_points(input: &amp;[Vec&lt;u64&gt;]) -&gt; Vec&lt;(usize, usize)&gt; {
   let mut result = find_saddle_points(input);
   result.sort();
   result
}

#[test]
fn identify_single_saddle_point() {
   let input = vec![vec![9, 8, 7], vec![5, 3, 2], vec![6, 6, 7]];
   assert_eq!(vec![(1, 0)], find_saddle_points(&amp;input));
}

#[test]
//#[ignore]
fn identify_empty_matrix() {
   let input = vec![vec![], vec![], vec![]];
   let expected: Vec&lt;(usize, usize)&gt; = Vec::new();
   assert_eq!(expected, find_saddle_points(&amp;input));
}

#[test]
//#[ignore]
fn identify_lack_of_saddle_point() {
   let input = vec![vec![1, 2, 3], vec![3, 1, 2], vec![2, 3, 1]];
   let expected: Vec&lt;(usize, usize)&gt; = Vec::new();
   assert_eq!(expected, find_saddle_points(&amp;input));
}

#[test]
//#[ignore]
fn multiple_saddle_points_in_col() {
   let input = vec![vec![4, 5, 4], vec![3, 5, 5], vec![1, 5, 4]];
   assert_eq!(
       vec![(0, 1), (1, 1), (2, 1)],
       find_sorted_saddle_points(&amp;input)
   );
}

#[test]
//#[ignore]
fn multiple_saddle_points_in_row() {
   let input = vec![vec![6, 7, 8], vec![5, 5, 5], vec![7, 5, 6]];
   assert_eq!(
       vec![(1, 0), (1, 1), (1, 2)],
       find_sorted_saddle_points(&amp;input)
   );
}

#[test]
//#[ignore]
fn identify_bottom_right_saddle_point() {
   let input = vec![vec![8, 7, 9], vec![6, 7, 6], vec![3, 2, 5]];
   assert_eq!(vec![(2, 2)], find_saddle_points(&amp;input));
}

// track specific as of v1.3
#[test]
//#[ignore]
fn non_square_matrix_high() {
   let input = vec![vec![1, 5], vec![3, 6], vec![2, 7], vec![3, 8]];
   assert_eq!(vec![(0, 1)], find_saddle_points(&amp;input));
}

#[test]
//#[ignore]
fn non_square_matrix_wide() {
   let input = vec![vec![3, 1, 3], vec![3, 2, 4]];
   assert_eq!(vec![(0, 0), (0, 2)], find_sorted_saddle_points(&amp;input));
}

#[test]
//#[ignore]
fn single_column_matrix() {
   let input = vec![vec![2], vec![1], vec![4], vec![1]];
   assert_eq!(vec![(1, 0), (3, 0)], find_saddle_points(&amp;input));
}

#[test]
//#[ignore]
fn single_row_matrix() {
   let input = vec![vec![2, 5, 3, 5]];
   assert_eq!(vec![(0, 1), (0, 3)], find_saddle_points(&amp;input));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-18" id="4-答案-18"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn find_saddle_points(input: &amp;[Vec&lt;u64&gt;]) -&gt; Vec&lt;(usize, usize)&gt; {
   let mut saddle_points = Vec::new();

   let width = input.len();
   let height = input[0].len();

   for i in 0..width {
       for j in 0..height {
           let column = input.iter().map(|x| x[j]).collect::&lt;Vec&lt;u64&gt;&gt;();
           let row = &amp;input[i];

           let max = row.iter().max().unwrap();
           let min = column.iter().min().unwrap();

           let value = input[i][j];

           if value &gt;= *max &amp;&amp; value &lt;= *min {
               saddle_points.push((i, j));
           }
       }
   }
   saddle_points
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-18" id="填充相关-18"><h2>填充/相关</h2></a>
<a class="header" href="#isogram" id="isogram"><h1>Isogram</h1></a>
<a class="header" href="#1-readme-19" id="1-readme-19"><h2>1. Readme</h2></a>
<a class="header" href="#等值线" id="等值线"><h1>等值线</h1></a>
<p>确定是否一词,或短语是等值线(<code>isograms</code>).</p>
<p>在等值线(又称为”无定形的 Word 是一个字或短语”)没有重复字母的单词或短语的逻辑术语，但允许连字符和空格出现多次。</p>
<p>等值线的例子:</p>
<ul>
<li>lumberjacks</li>
<li>background</li>
<li>downstream</li>
<li>six-year-old</li>
</ul>
<p>检测 <strong>isograms</strong> 单词，但它不是等值线,因为<code>s</code>重复了.</p>
<a class="header" href="#资源-10" id="资源-10"><h2>资源</h2></a>
<p>维基百科<a href="https://en.wikipedia.org/wiki/Isogram">https://en.wikipedia.org/wiki/Isogram</a></p>
<a class="header" href="#2-开始你的表演-19" id="2-开始你的表演-19"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn check(candidate: &amp;str) -&gt; bool {
   unimplemented!(&quot;Is {} an isogram?&quot;, candidate);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-19" id="3-测试代码查看-19"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn empty_string() {
   assert_eq!(check(&quot;&quot;), true, &quot;An empty string should be an isogram.&quot;)
}

#[test]
//#[ignore]
fn only_lower_case_characters() {
   assert_eq!(check(&quot;isogram&quot;), true, &quot;\&quot;isogram\&quot; should be an isogram.&quot;)
}

#[test]
//#[ignore]
fn one_duplicated_character() {
   assert_eq!(
       check(&quot;eleven&quot;),
       false,
       &quot;\&quot;eleven\&quot; has more than one \'e\', therefore it is no isogram.&quot;
   )
}

#[test]
//#[ignore]
fn longest_reported_english_isogram() {
   assert_eq!(
       check(&quot;subdermatoglyphic&quot;),
       true,
       &quot;\&quot;subdermatoglyphic\&quot; should be an isogram.&quot;
   )
}

#[test]
//#[ignore]
fn one_duplicated_character_mixed_case() {
   assert_eq!(
       check(&quot;Alphabet&quot;),
       false,
       &quot;\&quot;Alphabet\&quot; has more than one \'a\', therefore it is no isogram.&quot;
   )
}

#[test]
//#[ignore]
fn hypothetical_isogramic_word_with_hyphen() {
   assert_eq!(
       check(&quot;thumbscrew-japingly&quot;),
       true,
       &quot;\&quot;thumbscrew-japingly\&quot; should be an isogram.&quot;
   )
}

#[test]
//#[ignore]
fn isogram_with_duplicated_hyphen() {
   assert_eq!(
       check(&quot;six-year-old&quot;),
       true,
       &quot;\&quot;six-year-old\&quot; should be an isogram.&quot;
   )
}

#[test]
//#[ignore]
fn made_up_name_that_is_an_isogram() {
   assert_eq!(
       check(&quot;Emily Jung Schwartzkopf&quot;),
       true,
       &quot;\&quot;Emily Jung Schwartzkopf\&quot; should be an isogram.&quot;
   )
}

#[test]
//#[ignore]
fn duplicated_character_in_the_middle() {
   assert_eq!(
       check(&quot;accentor&quot;),
       false,
       &quot;\&quot;accentor\&quot; has more than one \'c\', therefore it is no isogram.&quot;
   )
}

#}</code></pre></pre>
<a class="header" href="#4-答案-19" id="4-答案-19"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn check(word: &amp;str) -&gt; bool {
   // Filter all non-Alphabetic character out and collect them in a new String
   let normalized_string: String = word.to_lowercase()
       .chars()
       .filter(|c| c.is_alphabetic())
       .collect();

   /* Find the char element from back and front and compare the index.
      If it is the same unique char the index will be the same.*/
   let is_unique = |x: char, word: &amp;str| word.find(x).unwrap() == word.rfind(x).unwrap();

   // Length should be the same if it is a isogram
   normalized_string.len()
       == normalized_string
           .chars()
           .filter(|&amp;x| is_unique(x, normalized_string.as_str()))
           .count()
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-19" id="填充相关-19"><h2>填充/相关</h2></a>
<a class="header" href="#say" id="say"><h1>Say</h1></a>
<a class="header" href="#1-readme-20" id="1-readme-20"><h2>1. Readme</h2></a>
<a class="header" href="#说" id="说"><h1>说</h1></a>
<p>提供一个 0 到 999,999,999,999 之间的数字,用英语拼出这个数字.</p>
<a class="header" href="#步骤-1-1" id="步骤-1-1"><h2>步骤 1</h2></a>
<p>处理 0 到 99 的基本情况.</p>
<p>如果程序的输入是<code>22</code>,那么输出应该是<code>'twenty-two'</code>.</p>
<p>如果给出超出规定范围的数字,您的程序应该大声抱怨。</p>
<p>这个程序的一些好的测试用例是:</p>
<ul>
<li><code>0</code></li>
<li><code>14</code></li>
<li><code>50</code></li>
<li><code>98</code></li>
<li><code>-1</code></li>
<li><code>100</code></li>
</ul>
<a class="header" href="#扩展" id="扩展"><h3>扩展</h3></a>
<p>如果您使用的是 Mac,那就是 Mac OS X 的 shell 可以用<code>say</code>程序大声说出来。如果您使用的是 Linux 或 Windows,则可以使用<code>espeak</code>命令使用 eSpeakNG.</p>
<a class="header" href="#第-2-步-1" id="第-2-步-1"><h2>第 2 步</h2></a>
<p>实现将数子分成块.</p>
<p>像<code>1234567890</code>，应该产生如 1,234,567 和 890 的列表,而更简单<code>1000</code>应该只产生 1 和 0.</p>
<p>该程序还必须报告超出范围的值。</p>
<a class="header" href="#第-3-步-1" id="第-3-步-1"><h2>第 3 步</h2></a>
<p>现在处理在这些块之间，插入适当的缩放词.</p>
<p>所以<code>1234567890</code>应该输出<code>'1 billion 234 million 567 thousand 890'</code></p>
<p>该程序还必须报告超出范围的值。上限为”兆（trillion）”处就可以.</p>
<a class="header" href="#第-4-步" id="第-4-步"><h2>第 4 步</h2></a>
<p>把它们放在一起，除了简单的英语之外什么都没有.</p>
<p><code>12345</code>应该给出<code>twelve thousand three hundred forty-five</code>.</p>
<p>该程序还必须报告超出范围的值.</p>
<a class="header" href="#扩展-1" id="扩展-1"><h3>扩展</h3></a>
<p>(正确地)使用英语<em>and</em>合并数字:</p>
<ul>
<li><code>14</code> =&gt; “fourteen”.</li>
<li><code>100</code> =&gt; “one hundred”.</li>
<li><code>120</code> =&gt; “one hundred and twenty”.</li>
<li><code>1002</code> =&gt; “one thousand and two”.</li>
<li><code>1323</code> =&gt; “one thousand three hundred and twenty-three”.</li>
</ul>
<a class="header" href="#特定的-rust-练习笔记" id="特定的-rust-练习笔记"><h2>特定的 Rust 练习笔记</h2></a>
<p>与本练习的其他语言版本相比,Rust 版本略有改变。我们使用 Rust 的强类型系统来限制输入,而不是要求您返回超出范围的错误。让函数处理所有有效输入要容易得多,而不是要求，使用模块的用户处理错误。</p>
<p>有一个 -1 版本的测试用例,但它被注释掉了。如果您的函数正确实现,则不应编译 -1 测试用例.</p>
<p>在测试用例中尚未实现，将”and”添加到数字文本中.</p>
<a class="header" href="#扩展-2" id="扩展-2"><h3>扩展</h3></a>
<p>添加转换为 u64 的最大值的功能:9,223,372,036,854,775,807.</p>
<p>有关输出的提示,请查看最后一个测试用例.</p>
<a class="header" href="#资源-11" id="资源-11"><h2>资源</h2></a>
<p>JavaRanch CattleDrive 的变体,练习 4a<a href="http://www.javaranch.com/say.jsp">http://www.javaranch.com/say.jsp</a></p>
<a class="header" href="#2-开始你的表演-20" id="2-开始你的表演-20"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn encode(n: u64) -&gt; String {
   unimplemented!(&quot;Say {} in English.&quot;, n);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-20" id="3-测试代码查看-20"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// Note: No tests created using 'and' with numbers.
// Apparently Most American English does not use the 'and' with numbers,
// where it is common in British English to use the 'and'.

#[test]
fn test_zero() {
   assert_eq!(encode(0), String::from(&quot;zero&quot;));
}

//
// If the below test is uncommented, it should not compile.
//
/*
#[test]
//#[ignore]
fn test_negative() {
   assert_eq!(encode(-1), String::from(&quot;won't compile&quot;));
}
*/

#[test]
//#[ignore]
fn test_one() {
   assert_eq!(encode(1), String::from(&quot;one&quot;));
}

#[test]
//#[ignore]
fn test_fourteen() {
   assert_eq!(encode(14), String::from(&quot;fourteen&quot;));
}

#[test]
//#[ignore]
fn test_twenty() {
   assert_eq!(encode(20), String::from(&quot;twenty&quot;));
}

#[test]
//#[ignore]
fn test_twenty_two() {
   assert_eq!(encode(22), String::from(&quot;twenty-two&quot;));
}

#[test]
//#[ignore]
fn test_one_hundred() {
   assert_eq!(encode(100), String::from(&quot;one hundred&quot;));
}

// note, using American style with no and
#[test]
//#[ignore]
fn test_one_hundred_twenty() {
   assert_eq!(encode(120), String::from(&quot;one hundred twenty&quot;));
}

#[test]
//#[ignore]
fn test_one_hundred_twenty_three() {
   assert_eq!(encode(123), String::from(&quot;one hundred twenty-three&quot;));
}

#[test]
//#[ignore]
fn test_one_thousand() {
   assert_eq!(encode(1000), String::from(&quot;one thousand&quot;));
}

#[test]
//#[ignore]
fn test_one_thousand_two_hundred_thirty_four() {
   assert_eq!(
       encode(1234),
       String::from(&quot;one thousand two hundred thirty-four&quot;)
   );
}

// note, using American style with no and
#[test]
//#[ignore]
fn test_eight_hundred_and_ten_thousand() {
   assert_eq!(encode(810_000), String::from(&quot;eight hundred ten thousand&quot;));
}

#[test]
//#[ignore]
fn test_one_million() {
   assert_eq!(encode(1_000_000), String::from(&quot;one million&quot;));
}

// note, using American style with no and
#[test]
//#[ignore]
fn test_one_million_two() {
   assert_eq!(encode(1_000_002), String::from(&quot;one million two&quot;));
}

#[test]
//#[ignore]
fn test_1002345() {
   assert_eq!(
       encode(1_002_345),
       String::from(&quot;one million two thousand three hundred forty-five&quot;)
   );
}

#[test]
//#[ignore]
fn test_one_billion() {
   assert_eq!(encode(1_000_000_000), String::from(&quot;one billion&quot;));
}

#[test]
//#[ignore]
fn test_987654321123() {
   assert_eq!(
       encode(987_654_321_123),
       String::from(
           &quot;nine hundred eighty-seven billion \
            six hundred fifty-four million \
            three hundred twenty-one thousand \
            one hundred twenty-three&quot;
       )
   );
}

/*
 These tests are only if you implemented full parsing for u64 type.
*/
#[test]
//#[ignore]
fn test_max_i64() {
   assert_eq!(
       encode(9_223_372_036_854_775_807),
       String::from(
           &quot;nine quintillion two hundred twenty-three \
            quadrillion three hundred seventy-two trillion \
            thirty-six billion eight hundred fifty-four million \
            seven hundred seventy-five thousand eight hundred seven&quot;
       )
   );
}

#[test]
//#[ignore]
fn test_max_u64() {
   assert_eq!(
       encode(18_446_744_073_709_551_615),
       String::from(
           &quot;eighteen quintillion four hundred forty-six \
            quadrillion seven hundred forty-four trillion \
            seventy-three billion seven hundred nine million \
            five hundred fifty-one thousand six hundred fifteen&quot;
       )
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-20" id="4-答案-20"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
const SMALL: &amp;'static [&amp;'static str] = &amp;[
   &quot;zero&quot;,
   &quot;one&quot;,
   &quot;two&quot;,
   &quot;three&quot;,
   &quot;four&quot;,
   &quot;five&quot;,
   &quot;six&quot;,
   &quot;seven&quot;,
   &quot;eight&quot;,
   &quot;nine&quot;,
   &quot;ten&quot;,
   &quot;eleven&quot;,
   &quot;twelve&quot;,
   &quot;thirteen&quot;,
   &quot;fourteen&quot;,
   &quot;fifteen&quot;,
   &quot;sixteen&quot;,
   &quot;seventeen&quot;,
   &quot;eighteen&quot;,
   &quot;nineteen&quot;,
];

const TENS: &amp;'static [&amp;'static str] = &amp;[
   &quot;ones&quot;, &quot;ten&quot;, &quot;twenty&quot;, &quot;thirty&quot;, &quot;forty&quot;, &quot;fifty&quot;, &quot;sixty&quot;, &quot;seventy&quot;, &quot;eighty&quot;, &quot;ninety&quot;,
];

const SCALE: &amp;'static [&amp;'static str] = &amp;[
   &quot;&quot;,
   &quot;thousand&quot;,
   &quot;million&quot;,
   &quot;billion&quot;,
   &quot;trillion&quot;,
   &quot;quadrillion&quot;,
   &quot;quintillion&quot;,
];

pub fn encode(n: u64) -&gt; String {
   if n &lt; 20 {
       SMALL[n as usize].to_string()
   } else if n &lt; 100 {
       let small = n % 10;
       let mut out = String::from(TENS[n as usize / 10]);
       if small &gt; 0 {
           out.push('-');
           out.push_str(SMALL[small as usize]);
       }
       out
   } else if n &lt; 1000 {
       let mut out = String::from(SMALL[n as usize / 100]);
       out.push_str(&quot; hundred&quot;);
       let ones = n % 100;
       if ones &gt; 0 {
           out.push(' ');
           out.push_str(&amp;encode(ones));
       }
       out
   } else {
       let mut sets: Vec&lt;u64&gt; = Vec::new();
       let mut val = n;
       while val &gt;= 1 {
           sets.push(val % 1000);
           val /= 1000;
       }
       let mut out = String::new();
       while let Some(modu) = sets.pop() {
           let len = sets.len();
           if modu == 0 {
               continue;
           }
           if out.len() &gt; 0 {
               out.push(' ');
           }
           out.push_str(&amp;encode(modu));
           if len &gt; 0 {
               out.push(' ');
               out.push_str(SCALE[len]);
           }
       }
       out
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-20" id="填充相关-20"><h2>填充/相关</h2></a>
<a class="header" href="#run-length-encoding" id="run-length-encoding"><h1>Run Length Encoding</h1></a>
<a class="header" href="#1-readme-21" id="1-readme-21"><h2>1. Readme</h2></a>
<a class="header" href="#运行游程编码" id="运行游程编码"><h1>运行游程编码</h1></a>
<p>实现编码和解码.</p>
<p>游程编码(RLE)是一种简单的数据压缩形式，其中运行的(连续数据元素)仅由一个数据值和计数代替。</p>
<p>例如,我们可以只用 13 字节，就可以 代表原始的 53 个字符.</p>
<pre><code class="language-text">&quot;WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB&quot;  -&gt;  &quot;12WB12W3B24WB&quot;
</code></pre>
<p>RLE 允许从压缩数据中，完美地重建原始数据,这使其成为无损数据压缩.</p>
<pre><code class="language-text">&quot;AABCCCDEEEE&quot;  -&gt;  &quot;2AB3CD4E&quot;  -&gt;  &quot;AABCCCDEEEE&quot;
</code></pre>
<p>为简单起见,您可以假设未编码的字符串，仅包含字母 A 到 Z(小写或大写)和空格。这样,要编码的数据将永远 <strong>不包含</strong> 任何数字,并且要解码的数据内的数字始终表示后续字符的计数。</p>
<a class="header" href="#资源-12" id="资源-12"><h2>资源</h2></a>
<p>维基百科<a href="https://en.wikipedia.org/wiki/Run-length_encoding">https://en.wikipedia.org/wiki/Run-length_encoding</a></p>
<a class="header" href="#2-开始你的表演-21" id="2-开始你的表演-21"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn encode(source: &amp;str) -&gt; String {
   unimplemented!(&quot;Return the run-length encoding of {}.&quot;, source);
}

pub fn decode(source: &amp;str) -&gt; String {
   unimplemented!(&quot;Return the run-length decoding of {}.&quot;, source);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-21" id="3-测试代码查看-21"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// encoding tests

#[test]
fn test_encode_empty_string() {
   assert_eq!(&quot;&quot;, encode(&quot;&quot;));
}

#[test]
//#[ignore]
fn test_encode_single_characters() {
   assert_eq!(&quot;XYZ&quot;, encode(&quot;XYZ&quot;));
}

#[test]
//#[ignore]
fn test_encode_string_with_no_single_characters() {
   assert_eq!(&quot;2A3B4C&quot;, encode(&quot;AABBBCCCC&quot;));
}

#[test]
//#[ignore]
fn test_encode_single_characters_mixed_with_repeated_characters() {
   assert_eq!(
       &quot;12WB12W3B24WB&quot;,
       encode(&quot;WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB&quot;)
   );
}

#[test]
//#[ignore]
fn test_encode_multiple_whitespace_mixed_in_string() {
   assert_eq!(&quot;2 hs2q q2w2 &quot;, encode(&quot;  hsqq qww  &quot;));
}

#[test]
//#[ignore]
fn test_encode_lowercase_characters() {
   assert_eq!(&quot;2a3b4c&quot;, encode(&quot;aabbbcccc&quot;));
}

// decoding tests

#[test]
//#[ignore]
fn test_decode_empty_string() {
   assert_eq!(&quot;&quot;, decode(&quot;&quot;));
}

#[test]
//#[ignore]
fn test_decode_single_characters_only() {
   assert_eq!(&quot;XYZ&quot;, decode(&quot;XYZ&quot;));
}

#[test]
//#[ignore]
fn test_decode_string_with_no_single_characters() {
   assert_eq!(&quot;AABBBCCCC&quot;, decode(&quot;2A3B4C&quot;));
}

#[test]
//#[ignore]
fn test_decode_single_characters_with_repeated_characters() {
   assert_eq!(
       &quot;WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB&quot;,
       decode(&quot;12WB12W3B24WB&quot;)
   );
}

#[test]
//#[ignore]
fn test_decode_multiple_whitespace_mixed_in_string() {
   assert_eq!(&quot;  hsqq qww  &quot;, decode(&quot;2 hs2q q2w2 &quot;));
}

#[test]
//#[ignore]
fn test_decode_lower_case_string() {
   assert_eq!(&quot;aabbbcccc&quot;, decode(&quot;2a3b4c&quot;));
}

// consistency test

#[test]
//#[ignore]
fn test_consistency() {
   assert_eq!(&quot;zzz ZZ  zZ&quot;, decode(encode(&quot;zzz ZZ  zZ&quot;).as_str()));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-21" id="4-答案-21"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::cmp;

pub fn encode(input: &amp;str) -&gt; String {
   input
       .chars()
       .fold(
           (String::new(), ' ', 0, 1),
           |(mut acc, last, last_n, pos), c| {
               // acc = where answer is accumulated
               // last = last character read
               // last_n = accum count for last
               if c == last {
                   if pos == input.len() {
                       // end of string
                       acc += (last_n + 1).to_string().as_str();
                       acc.push(c);
                   }
                   (acc, last, last_n + 1, pos + 1)
               } else {
                   if last_n &gt; 1 {
                       acc += last_n.to_string().as_str();
                   }
                   if last_n &gt; 0 {
                       // ignore initial last (single whitespace)
                       acc.push(last);
                   }
                   if pos == input.len() {
                       // end of string
                       acc.push(c);
                   }
                   (acc, c, 1, pos + 1)
               }
           },
       )
       .0
}

pub fn decode(input: &amp;str) -&gt; String {
   input
       .chars()
       .fold((String::new(), 0), |(mut acc, last_n), c| {
           if let Some(d) = c.to_digit(10) {
               (acc, 10 * last_n + d)
           } else {
               acc += c.to_string().repeat(cmp::max(last_n, 1) as usize).as_str();
               (acc, 0)
           }
       })
       .0
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-21" id="填充相关-21"><h2>填充/相关</h2></a>
<a class="header" href="#isbn-verifier" id="isbn-verifier"><h1>ISBN Verifier</h1></a>
<a class="header" href="#1-readme-22" id="1-readme-22"><h2>1. Readme</h2></a>
<a class="header" href="#isbn-检验器" id="isbn-检验器"><h1>ISBN 检验器</h1></a>
<p>这个<a href="https://en.wikipedia.org/wiki/International_Standard_Book_Number">ISBN-10 检测进程</a>用于验证图书识别号。通常包含破折号,看起来像:<code>3-598-21508-8</code></p>
<a class="header" href="#国际标准书号" id="国际标准书号"><h2>国际标准书号</h2></a>
<p>ISBN-10 格式是 9 位数字(0 到 9)加上一个校验字符(一个数字或一个 X)。在校验字符为 X 的情况下,这表示值”10”。这些可以与连字符(不管有没有)通信,并且可以通过以下公式检查它们的有效性:</p>
<pre><code>(x1 * 10 + x2 * 9 + x3 * 8 + x4 * 7 + x5 * 6 + x6 * 5 + x7 * 4 + x8 * 3 + x9 * 2 + x10 * 1) mod 11 == 0
</code></pre>
<p>如果结果是 0,那么它是一个有效的 ISBN-10,否则它是无效的.</p>
<a class="header" href="#例子-2" id="例子-2"><h2>例子</h2></a>
<p>让我们用 ISBN-10<code>3-598-21508-8</code>. 我们把它插入到公式中,得到:</p>
<pre><code>(3 * 10 + 5 * 9 + 9 * 8 + 8 * 7 + 2 * 6 + 1 * 5 + 5 * 4 + 0 * 3 + 8 * 2 + 8 * 1) mod 11 == 0
</code></pre>
<p>由于结果是 0,这证明我们的 ISBN 是有效的.</p>
<a class="header" href="#任务" id="任务"><h2>任务</h2></a>
<p>给定一个字符串,程序应该检查所提供的字符串是否是有效的 ISBN-10。为了实现这一点，需要在计算 ISBN 的校验位数之前，考虑字符串的预处理/解析.</p>
<p>该程序应该能够验证 ISBN-10 的破折号(不管有没有).</p>
<a class="header" href="#告诫" id="告诫"><h2>告诫</h2></a>
<p>在某些语言中,从字符串转换为数字可能是棘手的。现在,甚至更棘手的是,ISBN-10 的校验位可能是”X”(表示”10”).例如<code>3-598-21507-X</code>是一个有效的 ISBN-10.</p>
<a class="header" href="#奖金任务" id="奖金任务"><h2>奖金任务</h2></a>
<ul>
<li>
<p>从输入 ISBN-10 生成有效的 ISBN-13(并且可能用类似验证器再次验证它).</p>
</li>
<li>
<p>生成有效的 ISBN,甚至可能从给定的起始 ISBN 中生成.</p>
</li>
</ul>
<a class="header" href="#资源-13" id="资源-13"><h2>资源</h2></a>
<p>将一个字符串，转换成一个数字和一些基本的处理,利用一个可靠的真实世界的例子.<a href="https://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digit_calculation">https://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digit_calculation</a></p>
<a class="header" href="#2-开始你的表演-22" id="2-开始你的表演-22"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">/// Determines whether the supplied string is a valid ISBN number
pub fn is_valid_isbn(isbn: &amp;str) -&gt; bool {
   unimplemented!(&quot;Is {:?} a valid ISBN number?&quot;, isbn);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-22" id="3-测试代码查看-22"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_valid() {
   assert!(is_valid_isbn(&quot;3-598-21508-8&quot;));
}

#[test]
//#[ignore]
fn test_invalid_check_digit() {
   assert!(!is_valid_isbn(&quot;3-598-21508-9&quot;));
}

#[test]
//#[ignore]
fn test_valid_check_digit_of_10() {
   assert!(is_valid_isbn(&quot;3-598-21507-X&quot;));
}

#[test]
//#[ignore]
fn test_invalid_character_as_check_digit() {
   assert!(!is_valid_isbn(&quot;3-598-21507-A&quot;));
}

#[test]
//#[ignore]
fn test_invalid_character_in_isbn() {
   assert!(!is_valid_isbn(&quot;3-598-2K507-0&quot;));
}

#[test]
//#[ignore]
#[allow(non_snake_case)]
fn test_invalid_isbn_with_invalid_X() {
   assert!(!is_valid_isbn(&quot;3-598-2X507-9&quot;));
}

#[test]
//#[ignore]
fn test_valid_isbn_without_dashes() {
   assert!(is_valid_isbn(&quot;3598215088&quot;));
}

#[test]
//#[ignore]
#[allow(non_snake_case)]
fn test_valid_isbn_without_dashes_and_X_as_check() {
   assert!(is_valid_isbn(&quot;359821507X&quot;));
}

#[test]
//#[ignore]
fn test_invalid_isbn_without_dashes_and_no_check_digit() {
   assert!(!is_valid_isbn(&quot;359821507&quot;));
}

#[test]
//#[ignore]
fn test_invalid_isbn_without_dashes_and_too_long() {
   assert!(!is_valid_isbn(&quot;3598215078X&quot;));
}

#[test]
//#[ignore]
fn test_invalid_isbn_without_check_digit() {
   assert!(!is_valid_isbn(&quot;3-598-21507&quot;));
}

#[test]
//#[ignore]
fn test_invalid_isbn_too_long() {
   assert!(!is_valid_isbn(&quot;3-598-21507-XX&quot;));
}

#[test]
//#[ignore]
fn test_valid_digits_invalid_length() {
   assert!(!is_valid_isbn(&quot;35982150881&quot;));
}

#[test]
//#[ignore]
fn test_special_characters() {
   assert!(!is_valid_isbn(&quot;!@#%!@&quot;));
}

#[test]
//#[ignore]
#[allow(non_snake_case)]
fn test_invalid_isbn_with_check_digit_X_instead_of_0() {
   assert!(!is_valid_isbn(&quot;3-598-21515-X&quot;));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-22" id="4-答案-22"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
/// An ISBN type
#[derive(PartialEq, Eq)]
enum IsbnType {
   Isbn10,
   Isbn13,
}

/// Checks if an 'X' is valid at the given position for the given ISBN type
#[allow(non_snake_case)]
fn is_X_valid(position: &amp;usize, isbn_type: &amp;IsbnType) -&gt; bool {
   (isbn_type == &amp;IsbnType::Isbn10 &amp;&amp; position == &amp;9)
       || (isbn_type == &amp;IsbnType::Isbn13 &amp;&amp; position == &amp;12)
}

/// Checks if a '-' is valid at the given position for the given ISBN type
fn is_dash_valid(position: &amp;usize, isbn_type: &amp;IsbnType) -&gt; bool {
   isbn_type == &amp;IsbnType::Isbn13 &amp;&amp; (position == &amp;1 || position == &amp;5 || position == &amp;11)
}

/// Determines whether the supplied string is a valid ISBN number
pub fn is_valid_isbn(isbn: &amp;str) -&gt; bool {
   let isbn_type = match isbn.len() {
       10 =&gt; IsbnType::Isbn10,
       13 =&gt; IsbnType::Isbn13,
       _ =&gt; return false,
   };

   let mut checksum = 0;
   let mut coefficient = 10;
   for (position, c) in isbn.char_indices() {
       let digit_value = match c {
           '0'...'9' =&gt; c.to_digit(10).unwrap(),
           'X' if is_X_valid(&amp;position, &amp;isbn_type) =&gt; 10,
           '-' if is_dash_valid(&amp;position, &amp;isbn_type) =&gt; continue,
           _ =&gt; return false,
       };

       checksum += coefficient * digit_value;
       coefficient -= 1;
   }

   checksum % 11 == 0
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-22" id="填充相关-22"><h2>填充/相关</h2></a>
<a class="header" href="#perfect-numbers" id="perfect-numbers"><h1>Perfect Numbers</h1></a>
<a class="header" href="#1-readme-23" id="1-readme-23"><h2>1. Readme</h2></a>
<a class="header" href="#完全数" id="完全数"><h1>完全数</h1></a>
<p>根据 Nicomachus’(60-120CE)的自然数分类方案，确定一个数是- <strong>Perfect(完全)</strong>, <strong>Abundant(过剩数)</strong>, <strong>Deficient(亏数)</strong></p>
<p>希腊数学家<a href="https://en.wikipedia.org/wiki/Nicomachus">Nicomachus</a>设计了一种自然数的分类方案,将每一个数识别归类为 <strong>perfect</strong>, <strong>abundant</strong>, or <strong>deficient</strong> ，方案基于<a href="https://en.wikipedia.org/wiki/Aliquot_sum">aliquot sum（等值和）</a>。 等值和定义为不包括数字本身的约数(可除出整数)的总和。例如,15 的等值和是(1+3+5)=9.</p>
<ul>
<li><strong>Perfect(完全)</strong>: aliquot sum = number
<ul>
<li>6 ，因为 (1 + 2 + 3) = 6</li>
<li>28 ，因为 (1 + 2 + 4 + 7 + 14) = 28</li>
</ul>
</li>
<li><strong>Abundant(过剩数)</strong>: aliquot sum &gt; number
<ul>
<li>12 , 因为 (1 + 2 + 3 + 4 + 6) = 16</li>
<li>24 , 因为 (1 + 2 + 3 + 4 + 6 + 8 + 12) = 36</li>
</ul>
</li>
<li><strong>Deficient(亏数)</strong>: aliquot sum &lt; number
<ul>
<li>8 ， 因为 (1 + 2 + 4) = 7</li>
<li>素数 都是 deficient</li>
</ul>
</li>
</ul>
<p>实现一种方法来确定给定的数字是否为<strong>Perfect</strong>。 根据您的语言轨迹,您还可能需要实现一种方法来确定给定的数字是否为<strong>Abundant</strong>或<strong>Deficient</strong>.</p>
<a class="header" href="#资源-14" id="资源-14"><h2>资源</h2></a>
<p>取自 Neal Ford 的函数思维第 2 章.<a href="http://shop.oreilly.com/product/0636920029687.do">http://shop.oreilly.com/product/0636920029687.do</a></p>
<a class="header" href="#2-开始你的表演-23" id="2-开始你的表演-23"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">#[derive(Debug, PartialEq, Eq)]
pub enum Classification {
   Abundant,
   Perfect,
   Deficient,
}

pub fn classify(num: u64) -&gt; Option&lt;Classification&gt; {
   unimplemented!(&quot;classify {}&quot;, num);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-23" id="3-测试代码查看-23"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
macro_rules! tests {
   ($property_test_func:ident {
       $( $(#[$attr:meta])* $test_name:ident( $( $param:expr ),* ); )+
   }) =&gt; {
       $(
           $(#[$attr])*
           #[test]
           fn $test_name() {
               $property_test_func($( $param ),* )
           }
       )+
   }
}

fn test_classification(num: u64, result: Classification) {
   assert_eq!(classify(num), Some(result));
}

#[test]
fn basic() {
   assert_eq!(classify(0), None);
}

tests! {
   test_classification {
       test_1(1, Classification::Deficient);
       test_2(2, Classification::Deficient);
       test_4(4, Classification::Deficient);
       test_6(6, Classification::Perfect);
       test_12(12, Classification::Abundant);
       test_28(28, Classification::Perfect);
       test_30(30, Classification::Abundant);
       test_32(32, Classification::Deficient);
       test_33550335(33550335, Classification::Abundant);
       test_33550336(33550336, Classification::Perfect);
       test_33550337(33550337, Classification::Deficient);
   }
}

#}</code></pre></pre>
<a class="header" href="#4-答案-23" id="4-答案-23"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn classify(num: u64) -&gt; Option&lt;Classification&gt; {
   if num == 0 {
       return None;
   }
   let sum: u64 = (1..num).filter(|i| num % i == 0).sum();
   if sum == num {
       Some(Classification::Perfect)
   } else if sum &lt; num {
       Some(Classification::Deficient)
   } else {
       Some(Classification::Abundant)
   }
}

#[derive(Debug, PartialEq, Eq)]
pub enum Classification {
   Abundant,
   Perfect,
   Deficient,
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-23" id="填充相关-23"><h2>填充/相关</h2></a>
<a class="header" href="#clock" id="clock"><h1>Clock</h1></a>
<a class="header" href="#1-readme-24" id="1-readme-24"><h2>1. Readme</h2></a>
<a class="header" href="#时钟clock" id="时钟clock"><h1>时钟(Clock)</h1></a>
<p>实现一个处理没有日期的时间的 clock.</p>
<p>您应该可以添加和减去,分钟数.</p>
<p>代表相同时间的两个时钟应该彼此相等.</p>
<a class="header" href="#具有to_string的-rust-traits" id="具有to_string的-rust-traits"><h2>具有<code>.to_string()</code>的 Rust Traits</h2></a>
<p>你为 Clock 结构实现了<code>.to_string()</code>吗?</p>
<p>如果是这样,请尝试为 Clock 实现<a href="https://doc.rust-lang.org/std/fmt/trait.Display.html">Display trait(特征)</a></p>
<p>特征为各种类型的功能实现，提供了通用方法.</p>
<p>对于其他学习, 可以试试为 Clock 类型实现 <code>String::from</code>?</p>
<a class="header" href="#资源-15" id="资源-15"><h2>资源</h2></a>
<p>与 Erin Drummond 的配对会议<a href="https://twitter.com/ebdrummond">https://twitter.com/ebdrummond</a></p>
<a class="header" href="#2-开始你的表演-24" id="2-开始你的表演-24"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub struct Clock;

impl Clock {
   pub fn new(hours: i32, minutes: i32) -&gt; Self {
       unimplemented!(
           &quot;Construct a new Clock from {} hours and {} minutes&quot;,
           hours,
           minutes
       );
   }

   pub fn add_minutes(self, minutes: i32) -&gt; Self {
       unimplemented!(&quot;Add {} minutes to existing Clock time&quot;, minutes);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-24" id="3-测试代码查看-24"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
//
// Clock Creation
//

#[test]
fn test_on_the_hour() {
   assert_eq!(Clock::new(8, 0).to_string(), &quot;08:00&quot;);
}

#[test]
//#[ignore]
fn test_past_the_hour() {
   assert_eq!(Clock::new(11, 9).to_string(), &quot;11:09&quot;);
}

#[test]
//#[ignore]
fn test_midnight_is_zero_hours() {
   assert_eq!(Clock::new(24, 0).to_string(), &quot;00:00&quot;);
}

#[test]
//#[ignore]
fn test_hour_rolls_over() {
   assert_eq!(Clock::new(25, 0).to_string(), &quot;01:00&quot;);
}

#[test]
//#[ignore]
fn test_hour_rolls_over_continuously() {
   assert_eq!(Clock::new(100, 0).to_string(), &quot;04:00&quot;);
}

#[test]
//#[ignore]
fn test_sixty_minutes_is_next_hour() {
   assert_eq!(Clock::new(1, 60).to_string(), &quot;02:00&quot;);
}

#[test]
//#[ignore]
fn test_minutes_roll_over() {
   assert_eq!(Clock::new(0, 160).to_string(), &quot;02:40&quot;);
}

#[test]
//#[ignore]
fn test_minutes_roll_over_continuously() {
   assert_eq!(Clock::new(0, 1723).to_string(), &quot;04:43&quot;);
}

#[test]
//#[ignore]
fn test_hours_and_minutes_roll_over() {
   assert_eq!(Clock::new(25, 160).to_string(), &quot;03:40&quot;);
}

#[test]
//#[ignore]
fn test_hours_and_minutes_roll_over_continuously() {
   assert_eq!(Clock::new(201, 3001).to_string(), &quot;11:01&quot;);
}

#[test]
//#[ignore]
fn test_hours_and_minutes_roll_over_to_exactly_midnight() {
   assert_eq!(Clock::new(72, 8640).to_string(), &quot;00:00&quot;);
}

#[test]
//#[ignore]
fn test_negative_hour() {
   assert_eq!(Clock::new(-1, 15).to_string(), &quot;23:15&quot;);
}

#[test]
//#[ignore]
fn test_negative_hour_roll_over() {
   assert_eq!(Clock::new(-25, 00).to_string(), &quot;23:00&quot;);
}

#[test]
//#[ignore]
fn test_negative_hour_roll_over_continuously() {
   assert_eq!(Clock::new(-91, 00).to_string(), &quot;05:00&quot;);
}

#[test]
//#[ignore]
fn test_negative_minutes() {
   assert_eq!(Clock::new(1, -40).to_string(), &quot;00:20&quot;);
}

#[test]
//#[ignore]
fn test_negative_minutes_roll_over() {
   assert_eq!(Clock::new(1, -160).to_string(), &quot;22:20&quot;);
}

#[test]
//#[ignore]
fn test_negative_minutes_roll_over_continuously() {
   assert_eq!(Clock::new(1, -4820).to_string(), &quot;16:40&quot;);
}

#[test]
//#[ignore]
fn test_negative_hour_and_minutes_both_roll_over() {
   assert_eq!(Clock::new(-25, -160).to_string(), &quot;20:20&quot;);
}

#[test]
//#[ignore]
fn test_negative_hour_and_minutes_both_roll_over_continuously() {
   assert_eq!(Clock::new(-121, -5810).to_string(), &quot;22:10&quot;);
}

//
// Clock Math
//

#[test]
//#[ignore]
fn test_add_minutes() {
   let clock = Clock::new(10, 0).add_minutes(3);
   assert_eq!(clock.to_string(), &quot;10:03&quot;);
}

#[test]
//#[ignore]
fn test_add_no_minutes() {
   let clock = Clock::new(6, 41).add_minutes(0);
   assert_eq!(clock.to_string(), &quot;06:41&quot;);
}

#[test]
//#[ignore]
fn test_add_to_next_hour() {
   let clock = Clock::new(0, 45).add_minutes(40);
   assert_eq!(clock.to_string(), &quot;01:25&quot;);
}

#[test]
//#[ignore]
fn test_add_more_than_one_hour() {
   let clock = Clock::new(10, 0).add_minutes(61);
   assert_eq!(clock.to_string(), &quot;11:01&quot;);
}

#[test]
//#[ignore]
fn test_add_more_than_two_hours_with_carry() {
   let clock = Clock::new(0, 45).add_minutes(160);
   assert_eq!(clock.to_string(), &quot;03:25&quot;);
}

#[test]
//#[ignore]
fn test_add_across_midnight() {
   let clock = Clock::new(23, 59).add_minutes(2);
   assert_eq!(clock.to_string(), &quot;00:01&quot;);
}

#[test]
//#[ignore]
fn test_add_more_than_one_day() {
   let clock = Clock::new(5, 32).add_minutes(1500);
   assert_eq!(clock.to_string(), &quot;06:32&quot;);
}

#[test]
//#[ignore]
fn test_add_more_than_two_days() {
   let clock = Clock::new(1, 1).add_minutes(3500);
   assert_eq!(clock.to_string(), &quot;11:21&quot;);
}

#[test]
//#[ignore]
fn test_subtract_minutes() {
   let clock = Clock::new(10, 3).add_minutes(-3);
   assert_eq!(clock.to_string(), &quot;10:00&quot;);
}

#[test]
//#[ignore]
fn test_subtract_to_previous_hour() {
   let clock = Clock::new(10, 3).add_minutes(-30);
   assert_eq!(clock.to_string(), &quot;09:33&quot;);
}

#[test]
//#[ignore]
fn test_subtract_more_than_an_hour() {
   let clock = Clock::new(10, 3).add_minutes(-70);
   assert_eq!(clock.to_string(), &quot;08:53&quot;);
}

#[test]
//#[ignore]
fn test_subtract_across_midnight() {
   let clock = Clock::new(0, 3).add_minutes(-4);
   assert_eq!(clock.to_string(), &quot;23:59&quot;);
}

#[test]
//#[ignore]
fn test_subtract_more_than_two_hours() {
   let clock = Clock::new(0, 0).add_minutes(-160);
   assert_eq!(clock.to_string(), &quot;21:20&quot;);
}

#[test]
//#[ignore]
fn test_subtract_more_than_two_hours_with_borrow() {
   let clock = Clock::new(6, 15).add_minutes(-160);
   assert_eq!(clock.to_string(), &quot;03:35&quot;);
}

#[test]
//#[ignore]
fn test_subtract_more_than_one_day() {
   let clock = Clock::new(5, 32).add_minutes(-1500);
   assert_eq!(clock.to_string(), &quot;04:32&quot;);
}

#[test]
//#[ignore]
fn test_subtract_mores_than_two_days() {
   let clock = Clock::new(2, 20).add_minutes(-3000);
   assert_eq!(clock.to_string(), &quot;00:20&quot;);
}

//
// Test Equality
//

#[test]
//#[ignore]
fn test_compare_clocks_for_equality() {
   assert_eq!(Clock::new(15, 37), Clock::new(15, 37));
}

#[test]
//#[ignore]
fn test_compare_clocks_a_minute_apart() {
   assert_ne!(Clock::new(15, 36), Clock::new(15, 37));
}

#[test]
//#[ignore]
fn test_compare_clocks_an_hour_apart() {
   assert_ne!(Clock::new(14, 37), Clock::new(15, 37));
}

#[test]
//#[ignore]
fn test_compare_clocks_with_hour_overflow() {
   assert_eq!(Clock::new(10, 37), Clock::new(34, 37));
}

#[test]
//#[ignore]
fn test_compare_clocks_with_hour_overflow_by_several_days() {
   assert_eq!(Clock::new(3, 11), Clock::new(99, 11));
}

#[test]
//#[ignore]
fn test_compare_clocks_with_negative_hour() {
   assert_eq!(Clock::new(22, 40), Clock::new(-2, 40));
}

#[test]
//#[ignore]
fn test_compare_clocks_with_negative_hour_that_wraps() {
   assert_eq!(Clock::new(17, 3), Clock::new(-31, 3));
}

#[test]
//#[ignore]
fn test_compare_clocks_with_negative_hour_that_wraps_multiple_times() {
   assert_eq!(Clock::new(13, 49), Clock::new(-83, 49));
}

#[test]
//#[ignore]
fn test_compare_clocks_with_minutes_overflow() {
   assert_eq!(Clock::new(0, 1), Clock::new(0, 1441));
}

#[test]
//#[ignore]
fn test_compare_clocks_with_minutes_overflow_by_several_days() {
   assert_eq!(Clock::new(2, 2), Clock::new(2, 4322));
}

#[test]
//#[ignore]
fn test_compare_clocks_with_negative_minute() {
   assert_eq!(Clock::new(2, 40), Clock::new(3, -20))
}

#[test]
//#[ignore]
fn test_compare_clocks_with_negative_minute_that_wraps() {
   assert_eq!(Clock::new(4, 10), Clock::new(5, -1490))
}

#[test]
//#[ignore]
fn test_compare_clocks_with_negative_minute_that_wraps_multiple() {
   assert_eq!(Clock::new(6, 15), Clock::new(6, -4305))
}

#[test]
//#[ignore]
fn test_compare_clocks_with_negative_hours_and_minutes() {
   assert_eq!(Clock::new(7, 32), Clock::new(-12, -268))
}

#[test]
//#[ignore]
fn test_compare_clocks_with_negative_hours_and_minutes_that_wrap() {
   assert_eq!(Clock::new(18, 7), Clock::new(-54, -11513))
}

#[test]
//#[ignore]
fn test_compare_full_clock_and_zeroed_clock() {
   assert_eq!(Clock::new(24, 0), Clock::new(0, 0))
}

#}</code></pre></pre>
<a class="header" href="#4-答案-24" id="4-答案-24"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::fmt;

#[derive(Eq, PartialEq, Debug)]
pub struct Clock {
   minutes: i32,
}

impl fmt::Display for Clock {
   fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
       let hours = self.minutes / 60;
       let mins = self.minutes % 60;
       write!(f, &quot;{:02}:{:02}&quot;, hours, mins)
   }
}

impl Clock {
   pub fn new(hour: i32, minute: i32) -&gt; Self {
       Clock::build(hour * 60 + minute)
   }

   fn build(minutes: i32) -&gt; Self {
       let mut mins = minutes;
       while mins &lt; 0 {
           mins += 1440;
       }
       Clock {
           minutes: mins % 1440,
       }
   }

   pub fn add_minutes(&amp;mut self, minutes: i32) -&gt; Self {
       Clock::build(self.minutes + minutes)
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-24" id="填充相关-24"><h2>填充/相关</h2></a>
<a class="header" href="#dot-dsl" id="dot-dsl"><h1>DOT DSL</h1></a>
<a class="header" href="#1-readme-25" id="1-readme-25"><h2>1. Readme</h2></a>
<a class="header" href="#dot-dsl-1" id="dot-dsl-1"><h1>DOT DSL</h1></a>
<p>编写类似于 Graphviz 点语言的特定领域语言.</p>
<p>一个<a href="https://en.wikipedia.org/wiki/Domain-specific_language">Domain Specific Language
(DSL)</a>是针对特定域优化的小语言.</p>
<p>比如说<a href="https://en.wikipedia.org/wiki/DOT_(graph_description_language)">DOT 语言</a>允许您编写图形的文本描述，然后通过<a href="http://graphviz.org/">Graphviz</a>中其中一个图形工具(如<code>dot</code>)转换为图像，一个简单的图形如下所示:</p>
<pre><code>    graph {
        graph [bgcolor=&quot;yellow&quot;]
        a [color=&quot;red&quot;]
        b [color=&quot;blue&quot;]
        a -- b [color=&quot;green&quot;]
    }
</code></pre>
<p>把它放在一个<code>example.dot</code>文件中，并运行<code>dot example.dot -T png -o example.png</code>，就会创建一个图像<code>example.png</code>，其中黄色背景上的绿线连接的红色和蓝色圆圈。</p>
<p>创建类似于点语言的 DSL.</p>
<a class="header" href="#生成器模式builder-pattern" id="生成器模式builder-pattern"><h2>生成器模式(Builder pattern)</h2></a>
<p>本练习希望您通过使用<code>builder pattern</code>模式，构建多个结构。简而言之,此模式允许您将包含大量参数的结构的构造函数，拆分为多个单独的函数。这种方法为您提供了实现紧凑，但高度灵活的结构构造和配置的方法。你可以在<a href="https://doc.rust-lang.org/1.0.0/style/ownership/builders.html">该页面</a>上面阅读更多相关信息。</p>
<a class="header" href="#2-开始你的表演-25" id="2-开始你的表演-25"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub mod graph {
   pub struct Graph;

   impl Graph {
       pub fn new() -&gt; Self {
           unimplemented!(&quot;Construct a new Graph struct.&quot;);
       }
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-25" id="3-测试代码查看-25"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[macro_use]
extern crate maplit;

use graph::graph_items::edge::Edge;
use graph::graph_items::node::Node;
use graph::Graph;

#[test]
fn test_empty_graph() {
   let graph = Graph::new();

   assert!(graph.nodes.is_empty());

   assert!(graph.edges.is_empty());

   assert!(graph.attrs.is_empty());
}

#[test]
//#[ignore]
fn test_graph_with_one_node() {
   let nodes = vec![Node::new(&quot;a&quot;)];

   let graph = Graph::new().with_nodes(&amp;nodes);

   assert!(graph.edges.is_empty());

   assert!(graph.attrs.is_empty());

   assert_eq!(graph.nodes, vec![Node::new(&quot;a&quot;)]);
}

#[test]
//#[ignore]
fn test_graph_with_one_node_with_keywords() {
   let nodes = vec![Node::new(&quot;a&quot;).with_attrs(&amp;[(&quot;color&quot;, &quot;green&quot;)])];

   let graph = Graph::new().with_nodes(&amp;nodes);

   assert!(graph.edges.is_empty());

   assert!(graph.attrs.is_empty());

   assert_eq!(
       graph.nodes,
       vec![Node::new(&quot;a&quot;).with_attrs(&amp;[(&quot;color&quot;, &quot;green&quot;)])]
   );
}

#[test]
//#[ignore]
fn test_graph_with_one_edge() {
   let edges = vec![Edge::new(&quot;a&quot;, &quot;b&quot;)];

   let graph = Graph::new().with_edges(&amp;edges);

   assert!(graph.nodes.is_empty());

   assert!(graph.attrs.is_empty());

   assert_eq!(graph.edges, vec![Edge::new(&quot;a&quot;, &quot;b&quot;)]);
}

#[test]
//#[ignore]
fn test_graph_with_one_attribute() {
   let graph = Graph::new().with_attrs(&amp;[(&quot;foo&quot;, &quot;1&quot;)]);

   let expected_attrs = hashmap!{
       &quot;foo&quot;.to_string() =&gt; &quot;1&quot;.to_string(),
   };

   assert!(graph.nodes.is_empty());

   assert!(graph.edges.is_empty());

   assert_eq!(graph.attrs, expected_attrs);
}

#[test]
//#[ignore]
fn test_graph_with_attributes() {
   let nodes = vec![
       Node::new(&quot;a&quot;).with_attrs(&amp;[(&quot;color&quot;, &quot;green&quot;)]),
       Node::new(&quot;c&quot;),
       Node::new(&quot;b&quot;).with_attrs(&amp;[(&quot;label&quot;, &quot;Beta!&quot;)]),
   ];

   let edges = vec![
       Edge::new(&quot;b&quot;, &quot;c&quot;),
       Edge::new(&quot;a&quot;, &quot;b&quot;).with_attrs(&amp;[(&quot;color&quot;, &quot;blue&quot;)]),
   ];

   let attrs = vec![(&quot;foo&quot;, &quot;1&quot;), (&quot;title&quot;, &quot;Testing Attrs&quot;), (&quot;bar&quot;, &quot;true&quot;)];

   let expected_attrs = hashmap! {
       &quot;foo&quot;.to_string() =&gt; &quot;1&quot;.to_string(),
       &quot;title&quot;.to_string() =&gt; &quot;Testing Attrs&quot;.to_string(),
       &quot;bar&quot;.to_string() =&gt; &quot;true&quot;.to_string(),
   };

   let graph = Graph::new()
       .with_nodes(&amp;nodes)
       .with_edges(&amp;edges)
       .with_attrs(&amp;attrs);

   assert_eq!(
       graph.nodes,
       vec![
           Node::new(&quot;a&quot;).with_attrs(&amp;[(&quot;color&quot;, &quot;green&quot;)]),
           Node::new(&quot;c&quot;),
           Node::new(&quot;b&quot;).with_attrs(&amp;[(&quot;label&quot;, &quot;Beta!&quot;)]),
       ]
   );

   assert_eq!(
       graph.edges,
       vec![
           Edge::new(&quot;b&quot;, &quot;c&quot;),
           Edge::new(&quot;a&quot;, &quot;b&quot;).with_attrs(&amp;[(&quot;color&quot;, &quot;blue&quot;)]),
       ]
   );

   assert_eq!(graph.attrs, expected_attrs);
}

#[test]
//#[ignore]
fn test_graph_stores_attributes() {
   let attributes = [(&quot;foo&quot;, &quot;bar&quot;), (&quot;bat&quot;, &quot;baz&quot;), (&quot;bim&quot;, &quot;bef&quot;)];
   let graph = Graph::new().with_nodes(
       &amp;['a', 'b', 'c']
           .iter()
           .enumerate()
           .map(|(i, n)| Node::new(&amp;n.to_string()).with_attrs(&amp;attributes[i..i + 1]))
           .collect::&lt;Vec&lt;_&gt;&gt;(),
   );

   assert_eq!(
       graph
           .get_node(&quot;c&quot;)
           .expect(&quot;node must be stored&quot;)
           .get_attr(&quot;bim&quot;),
       Some(&quot;bef&quot;)
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-25" id="4-答案-25"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub mod graph {
   use std::collections::HashMap;

   use self::graph_items::edge::Edge;
   use self::graph_items::node::Node;

   pub struct Graph {
       pub nodes: Vec&lt;Node&gt;,
       pub edges: Vec&lt;Edge&gt;,
       pub attrs: HashMap&lt;String, String&gt;,
   }

   impl Graph {
       pub fn new() -&gt; Self {
           Graph {
               nodes: vec![],
               edges: vec![],
               attrs: HashMap::new(),
           }
       }

       pub fn with_nodes(mut self, nodes: &amp;[Node]) -&gt; Self {
           self.nodes = nodes.clone().to_vec();

           self
       }

       pub fn with_edges(mut self, edges: &amp;[Edge]) -&gt; Self {
           self.edges = edges.clone().to_vec();

           self
       }

       pub fn with_attrs(mut self, attrs: &amp;[(&amp;'static str, &amp;'static str)]) -&gt; Self {
           attrs.iter().for_each(|&amp;(name, value)| {
               self.attrs.insert(name.to_string(), value.to_string());
           });

           self
       }

       pub fn get_node(&amp;self, name: &amp;str) -&gt; Option&lt;&amp;Node&gt; {
           self.nodes.iter().filter(|n| n.name == name).nth(0)
       }
   }

   pub mod graph_items {
       pub mod edge {
           use std::collections::HashMap;

           #[derive(Clone, PartialEq, Debug)]
           pub struct Edge {
               src: String,
               dst: String,
               attrs: HashMap&lt;String, String&gt;,
           }

           impl Edge {
               pub fn new(src: &amp;str, dst: &amp;str) -&gt; Self {
                   Edge {
                       src: src.to_string(),
                       dst: dst.to_string(),
                       attrs: HashMap::new(),
                   }
               }

               pub fn with_attrs(mut self, attrs: &amp;[(&amp;'static str, &amp;'static str)]) -&gt; Self {
                   attrs.iter().for_each(|&amp;(name, value)| {
                       self.attrs.insert(name.to_string(), value.to_string());
                   });

                   self
               }
           }
       }

       pub mod node {
           use std::collections::HashMap;

           #[derive(Clone, PartialEq, Debug)]
           pub struct Node {
               pub name: String,

               attrs: HashMap&lt;String, String&gt;,
           }

           impl Node {
               pub fn new(name: &amp;str) -&gt; Self {
                   Node {
                       name: name.to_string(),
                       attrs: HashMap::new(),
                   }
               }

               pub fn with_attrs(mut self, attrs: &amp;[(&amp;'static str, &amp;'static str)]) -&gt; Self {
                   attrs.iter().for_each(|&amp;(name, value)| {
                       self.attrs.insert(name.to_string(), value.to_string());
                   });

                   self
               }

               pub fn get_attr(&amp;self, name: &amp;str) -&gt; Option&lt;&amp;str&gt; {
                   self.attrs.get(name).map(|v| v.as_ref())
               }
           }

       }
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-25" id="填充相关-25"><h2>填充/相关</h2></a>
<a class="header" href="#hamming" id="hamming"><h1>Hamming</h1></a>
<a class="header" href="#1-readme-26" id="1-readme-26"><h2>1. Readme</h2></a>
<a class="header" href="#汉明hamming" id="汉明hamming"><h1>汉明（Hamming）</h1></a>
<p>给 2 个长度为 n 的 DNA 序列，求汉明距离差异为多少。</p>
<p>通过比较两条 DNA 链,并计算其中有多少核苷酸与其他序列中的同等核苷酸不同.</p>
<pre><code>GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^ ^ ^ ^^
</code></pre>
<p>这两条 DNA 链之间的 汉明距离为 7.</p>
<a class="header" href="#实现说明" id="实现说明"><h1>实现说明</h1></a>
<p>汉明长度仅定义为等长的序列，因此尝试计算不同长度的序列之间的汉明 距离不应该起作用。这种情况的一般处理(例如,引发异常与返回特殊值)可能在语言之间有所不同.</p>
<a class="header" href="#资源-16" id="资源-16"><h2>资源</h2></a>
<p>罗瑟琳的计算点突变问题<a href="http://rosalind.info/problems/hamm/">http://rosalind.info/problems/hamm/</a></p>
<a class="header" href="#2-开始你的表演-26" id="2-开始你的表演-26"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">/// Return the Hamming distance between the strings,
/// or None if the lengths are mismatched.
pub fn hamming_distance(s1: &amp;str, s2: &amp;str) -&gt; Option&lt;usize&gt; {
   unimplemented!(&quot;What is the Hamming Distance between {:?} and {:?}&quot;, s1, s2);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-26" id="3-测试代码查看-26"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_no_difference_between_empty_strands() {
   assert_eq!(hamming_distance(&quot;&quot;, &quot;&quot;), Some(0));
}

#[test]
//#[ignore]
fn test_no_difference_between_identical_strands() {
   assert_eq!(hamming_distance(&quot;GGACTGA&quot;, &quot;GGACTGA&quot;), Some(0));
}

#[test]
//#[ignore]
fn test_complete_hamming_distance_in_small_strand() {
   assert_eq!(hamming_distance(&quot;ACT&quot;, &quot;GGA&quot;), Some(3));
}

#[test]
//#[ignore]
fn test_small_hamming_distance_in_the_middle_somewhere() {
   assert_eq!(hamming_distance(&quot;GGACG&quot;, &quot;GGTCG&quot;), Some(1));
}

#[test]
//#[ignore]
fn test_larger_distance() {
   assert_eq!(hamming_distance(&quot;ACCAGGG&quot;, &quot;ACTATGG&quot;), Some(2));
}

#[test]
//#[ignore]
fn test_first_string_is_longer() {
   assert_eq!(hamming_distance(&quot;AAA&quot;, &quot;AA&quot;), None);
}

#[test]
//#[ignore]
fn test_second_string_is_longer() {
   assert_eq!(hamming_distance(&quot;A&quot;, &quot;AA&quot;), None);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-26" id="4-答案-26"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn hamming_distance(a: &amp;str, b: &amp;str) -&gt; Option&lt;usize&gt; {
   if a.len() != b.len() {
       return None;
   }

   Some(a.chars().zip(b.chars()).filter(|&amp;(a, b)| a != b).count())
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-26" id="填充相关-26"><h2>填充/相关</h2></a>
<a class="header" href="#simple-linked-list" id="simple-linked-list"><h1>Simple Linked List</h1></a>
<a class="header" href="#1-readme-27" id="1-readme-27"><h2>1. Readme</h2></a>
<a class="header" href="#简单链表" id="简单链表"><h1>简单链表</h1></a>
<p>编写一个使用元素(<code>Elements</code>)和列表(<code>List</code>)的简单链表实现.</p>
<p>链表是计算机科学中的一种基本数据结构，常用于其他数据结构的实现。它们在函数式编程语言(如 Clojure、Erlang 或 Haskell)中很普遍，但是在命令式语言(如 Ruby 或 Python)中很少见。</p>
<p>最简单的链表是单链表。列表中的每个元素，包含数据和一个”next”字段，指向元素列表中的下一个元素。</p>
<p>链接列表的这种变体通常用于表示序列，或推/取堆栈(也称为 LIFO 堆栈;后进先出)。</p>
<p>作为第一步,让我们创建一个包含范围(1..10)的单一链接列表,并提供反转链接列表，和转换为数组，或从数组转换的函数.</p>
<p>在使用内置链表的语言实现这一点时,实现自己的抽象数据类型.</p>
<a class="header" href="#实现提示" id="实现提示"><h2>实现提示</h2></a>
<p>不要实现结构<code>SimpleLinkedList</code>作为一个<code>Vec</code>包装。 你应该,在堆上分配节点。
这可以实现为:</p>
<pre><pre class="playpen"><code class="language-rust no_run">
# #![allow(unused_variables)]
#fn main() {
pub struct SimpleLinkedList&lt;T&gt; {
    head: Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;,
}
#}</code></pre></pre>
<p>这个<code>head</code>字段指向该链表的第一个元素(节点)。
这个实现也需要一个<code>Node</code>结构，其具有以下字段:</p>
<pre><pre class="playpen"><code class="language-rust no_run">
# #![allow(unused_variables)]
#fn main() {
struct Node&lt;T&gt; {
    data: T,
    next: Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;,
}
#}</code></pre></pre>
<p><code>data</code>包含存储的数据,以及<code>next</code>指向下节点(如果可用)或无.</p>
<a class="header" href="#为什么使用optionboxnodet而不仅用optionnodet" id="为什么使用optionboxnodet而不仅用optionnodet"><h3>为什么使用<code>Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;</code>?而不仅用<code>Option&lt;Node&lt;T&gt;&gt;</code>?</h3></a>
<p>自己试试.您将得到以下错误.</p>
<pre><code>| struct Node&lt;T&gt;
| ^^^^^^^^^^^^^^ recursive type has infinite size
...
| next: Option&lt;Node&lt;T&gt;&gt;,
| --------------------- recursive without indirection
</code></pre>
<p>这个错误在于,编译时,rust 必须知道下一个节点的大小。因<code>next</code>会是递归的(”一个节点，有一个节点-有一个节点…”)，编译器不知道要分配多少内存。相反,<a href="https://doc.rust-lang.org/std/boxed/">Box</a>是一个具有定义大小的堆指针.</p>
<a class="header" href="#资源-17" id="资源-17"><h2>资源</h2></a>
<p>受”Ruby”中面向对象设计模式的数据结构和算法的启发,即单链表.<a href="http://www.brpreiss.com/books/opus8/html/page96.html#SECTION004300000000000000000">http://www.brpreiss.com/books/opus8/html/page96.html#SECTION004300000000000000000</a></p>
<a class="header" href="#2-开始你的表演-27" id="2-开始你的表演-27"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub struct SimpleLinkedList&lt;T&gt; {
   // Delete this field
   // dummy is needed to avoid unused parameter error during compilation
   dummy: ::std::marker::PhantomData&lt;T&gt;,
}

impl&lt;T&gt; SimpleLinkedList&lt;T&gt; {
   pub fn new() -&gt; Self {
       unimplemented!()
   }

   pub fn len(&amp;self) -&gt; usize {
       unimplemented!()
   }

   pub fn push(&amp;mut self, _element: T) {
       unimplemented!()
   }

   pub fn pop(&amp;mut self) -&gt; Option&lt;T&gt; {
       unimplemented!()
   }

   pub fn peek(&amp;self) -&gt; Option&lt;&amp;T&gt; {
       unimplemented!()
   }
}

impl&lt;T: Clone&gt; SimpleLinkedList&lt;T&gt; {
   pub fn rev(&amp;self) -&gt; SimpleLinkedList&lt;T&gt; {
       unimplemented!()
   }
}

impl&lt;'a, T: Clone&gt; From&lt;&amp;'a [T]&gt; for SimpleLinkedList&lt;T&gt; {
   fn from(_item: &amp;[T]) -&gt; Self {
       unimplemented!()
   }
}

impl&lt;T&gt; Into&lt;Vec&lt;T&gt;&gt; for SimpleLinkedList&lt;T&gt; {
   fn into(self) -&gt; Vec&lt;T&gt; {
       unimplemented!()
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-27" id="3-测试代码查看-27"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_new_list_is_empty() {
   let list: SimpleLinkedList&lt;u32&gt; = SimpleLinkedList::new();
   assert_eq!(list.len(), 0, &quot;list's length must be 0&quot;);
}

#[test]
//#[ignore]
fn test_push_increments_length() {
   let mut list: SimpleLinkedList&lt;u32&gt; = SimpleLinkedList::new();
   list.push(1);
   assert_eq!(list.len(), 1, &quot;list's length must be 1&quot;);
   list.push(2);
   assert_eq!(list.len(), 2, &quot;list's length must be 2&quot;);
}

#[test]
//#[ignore]
fn test_pop_decrements_length() {
   let mut list: SimpleLinkedList&lt;u32&gt; = SimpleLinkedList::new();
   list.push(1);
   list.push(2);
   list.pop();
   assert_eq!(list.len(), 1, &quot;list's length must be 1&quot;);
   list.pop();
   assert_eq!(list.len(), 0, &quot;list's length must be 0&quot;);
}

#[test]
//#[ignore]
fn test_pop_returns_last_added_element() {
   let mut list: SimpleLinkedList&lt;u32&gt; = SimpleLinkedList::new();
   list.push(1);
   list.push(2);
   assert_eq!(list.pop(), Some(2), &quot;Element must be 2&quot;);
   assert_eq!(list.pop(), Some(1), &quot;Element must be 1&quot;);
   assert_eq!(list.pop(), None, &quot;No element should be contained in list&quot;);
}

#[test]
//#[ignore]
fn test_peek_returns_head_element() {
   let mut list: SimpleLinkedList&lt;u32&gt; = SimpleLinkedList::new();
   assert_eq!(list.peek(), None, &quot;No element should be contained in list&quot;);
   list.push(2);
   assert_eq!(list.peek(), Some(&amp;2), &quot;Element must be 2&quot;);
   assert_eq!(list.peek(), Some(&amp;2), &quot;Element must be still 2&quot;);
}

#[test]
//#[ignore]
fn test_from_slice() {
   let array = [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;];
   let mut list = SimpleLinkedList::from(array.as_ref());
   assert_eq!(list.pop(), Some(&quot;4&quot;));
   assert_eq!(list.pop(), Some(&quot;3&quot;));
   assert_eq!(list.pop(), Some(&quot;2&quot;));
   assert_eq!(list.pop(), Some(&quot;1&quot;));
}

#[test]
//#[ignore]
fn test_reverse() {
   let mut list: SimpleLinkedList&lt;u32&gt; = SimpleLinkedList::new();
   list.push(1);
   list.push(2);
   list.push(3);
   let mut rev_list = list.rev();
   assert_eq!(rev_list.pop(), Some(1));
   assert_eq!(rev_list.pop(), Some(2));
   assert_eq!(rev_list.pop(), Some(3));
   assert_eq!(rev_list.pop(), None);
}

#[test]
//#[ignore]
fn test_into_vector() {
   let mut v = Vec::new();
   let mut s = SimpleLinkedList::new();
   for i in 1..4 {
       v.push(i);
       s.push(i);
   }
   let s_as_vec: Vec&lt;i32&gt; = s.into();
   assert_eq!(v, s_as_vec);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-27" id="4-答案-27"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub struct SimpleLinkedList&lt;T&gt; {
   head: Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;,
   len: usize,
}

struct Node&lt;T&gt; {
   data: T,
   next: Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;,
}

impl&lt;T&gt; SimpleLinkedList&lt;T&gt; {
   pub fn new() -&gt; Self {
       SimpleLinkedList { head: None, len: 0 }
   }

   pub fn len(&amp;self) -&gt; usize {
       self.len
   }

   pub fn push(&amp;mut self, element: T) {
       let node = Box::new(Node::new(element, self.head.take()));
       self.head = Some(node);
       self.len += 1;
   }

   pub fn pop(&amp;mut self) -&gt; Option&lt;T&gt; {
       match self.len {
           0 =&gt; None,
           _ =&gt; {
               self.len -= 1;
               self.head.take().map(|node| {
                   let node = *node;
                   self.head = node.next;
                   node.data
               })
           }
       }
   }

   pub fn peek(&amp;self) -&gt; Option&lt;&amp;T&gt; {
       self.head.as_ref().map(|node| &amp;node.data)
   }
}

impl&lt;T: Clone&gt; SimpleLinkedList&lt;T&gt; {
   pub fn rev(&amp;self) -&gt; SimpleLinkedList&lt;T&gt; {
       let mut rev_list = SimpleLinkedList::new();
       let mut next = self.head.as_ref().map(|node| &amp;**node);
       while let Some(node) = next {
           rev_list.push(node.data.clone());
           next = node.next.as_ref().map(|node| &amp;**node);
       }
       rev_list
   }
}

impl&lt;'a, T: Clone&gt; From&lt;&amp;'a [T]&gt; for SimpleLinkedList&lt;T&gt; {
   fn from(item: &amp;[T]) -&gt; Self {
       let mut list = SimpleLinkedList::new();
       for i in item {
           list.push(i.clone());
       }
       list
   }
}

impl&lt;T&gt; Into&lt;Vec&lt;T&gt;&gt; for SimpleLinkedList&lt;T&gt; {
   fn into(mut self) -&gt; Vec&lt;T&gt; {
       let mut vec = Vec::new();
       while let Some(data) = self.pop() {
           vec.push(data);
       }
       vec.reverse();
       vec
   }
}

impl&lt;T&gt; Node&lt;T&gt; {
   pub fn new(element: T, next: Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;) -&gt; Self {
       Node {
           data: element,
           next,
       }
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-27" id="填充相关-27"><h2>填充/相关</h2></a>
<a class="header" href="#pascals-triangle" id="pascals-triangle"><h1>pascals-triangle</h1></a>
<a class="header" href="#1-readme-28" id="1-readme-28"><h2>1. Readme</h2></a>
<a class="header" href="#杨辉三角形" id="杨辉三角形"><h1>杨辉三角形</h1></a>
<p>计算给定的行数的 杨辉三角形。</p>
<p>在 杨辉 三角形中, 可以看到，一个数由它头顶左右两个数相加得到的。</p>
<pre><code class="language-text">    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1
# ... etc
</code></pre>
<a class="header" href="#资源-18" id="资源-18"><h2>资源</h2></a>
<p>在数学世界的杨辉三角形<a href="http://mathworld.wolfram.com/PascalsTriangle.html">http://mathworld.wolfram.com/PascalsTriangle.html</a></p>
<p>维基百科<a href="https://zh.wikipedia.org/wiki/%E6%9D%A8%E8%BE%89%E4%B8%89%E8%A7%92%E5%BD%A2">https://zh.wikipedia.org/wiki/杨辉三角形</a></p>
<a class="header" href="#2-开始你的表演-28" id="2-开始你的表演-28"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub struct PascalsTriangle;

impl PascalsTriangle {
   pub fn new(row_count: u32) -&gt; Self {
       unimplemented!(&quot;create Pascal's triangle with {} rows&quot;, row_count);
   }

   pub fn rows(&amp;self) -&gt; Vec&lt;Vec&lt;u32&gt;&gt; {
       unimplemented!();
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-28" id="3-测试代码查看-28"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn no_rows() {
   let pt = PascalsTriangle::new(0);
   let expected: Vec&lt;Vec&lt;u32&gt;&gt; = Vec::new();
   assert_eq!(expected, pt.rows());
}

#[test]
//#[ignore]
fn one_row() {
   let pt = PascalsTriangle::new(1);
   let expected: Vec&lt;Vec&lt;u32&gt;&gt; = vec![vec![1]];
   assert_eq!(expected, pt.rows());
}

#[test]
//#[ignore]
fn two_rows() {
   let pt = PascalsTriangle::new(2);
   let expected: Vec&lt;Vec&lt;u32&gt;&gt; = vec![vec![1], vec![1, 1]];
   assert_eq!(expected, pt.rows());
}

#[test]
//#[ignore]
fn three_rows() {
   let pt = PascalsTriangle::new(3);
   let expected: Vec&lt;Vec&lt;u32&gt;&gt; = vec![vec![1], vec![1, 1], vec![1, 2, 1]];
   assert_eq!(expected, pt.rows());
}

#[test]
//#[ignore]
fn last_of_four_rows() {
   let pt = PascalsTriangle::new(4);
   let expected: Vec&lt;u32&gt; = vec![1, 3, 3, 1];
   assert_eq!(Some(expected), pt.rows().pop());
}

#[test]
//#[ignore]
fn five_rows() {
   let pt = PascalsTriangle::new(5);
   let expected: Vec&lt;Vec&lt;u32&gt;&gt; = vec![
       vec![1],
       vec![1, 1],
       vec![1, 2, 1],
       vec![1, 3, 3, 1],
       vec![1, 4, 6, 4, 1],
   ];
   assert_eq!(expected, pt.rows());
}

#[test]
//#[ignore]
fn six_rows() {
   let pt = PascalsTriangle::new(6);
   let expected: Vec&lt;Vec&lt;u32&gt;&gt; = vec![
       vec![1],
       vec![1, 1],
       vec![1, 2, 1],
       vec![1, 3, 3, 1],
       vec![1, 4, 6, 4, 1],
       vec![1, 5, 10, 10, 5, 1],
   ];
   assert_eq!(expected, pt.rows());
}

#[test]
//#[ignore]
fn seven_rows() {
   let pt = PascalsTriangle::new(7);
   let expected: Vec&lt;Vec&lt;u32&gt;&gt; = vec![
       vec![1],
       vec![1, 1],
       vec![1, 2, 1],
       vec![1, 3, 3, 1],
       vec![1, 4, 6, 4, 1],
       vec![1, 5, 10, 10, 5, 1],
       vec![1, 6, 15, 20, 15, 6, 1],
   ];
   assert_eq!(expected, pt.rows());
}

#[test]
//#[ignore]
fn ten_rows() {
   let pt = PascalsTriangle::new(10);
   let expected: Vec&lt;Vec&lt;u32&gt;&gt; = vec![
       vec![1],
       vec![1, 1],
       vec![1, 2, 1],
       vec![1, 3, 3, 1],
       vec![1, 4, 6, 4, 1],
       vec![1, 5, 10, 10, 5, 1],
       vec![1, 6, 15, 20, 15, 6, 1],
       vec![1, 7, 21, 35, 35, 21, 7, 1],
       vec![1, 8, 28, 56, 70, 56, 28, 8, 1],
       vec![1, 9, 36, 84, 126, 126, 84, 36, 9, 1],
   ];
   assert_eq!(expected, pt.rows());
}

#}</code></pre></pre>
<a class="header" href="#4-答案-28" id="4-答案-28"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub struct PascalsTriangle {
   row_count: u32,
}

impl PascalsTriangle {
   pub fn new(row_count: u32) -&gt; Self {
       PascalsTriangle {
           row_count: row_count,
       }
   }

   pub fn rows(&amp;self) -&gt; Vec&lt;Vec&lt;u32&gt;&gt; {
       (0..self.row_count)
           .map(|row| PascalsTriangle::row(row))
           .collect()
   }

   pub fn row(number: u32) -&gt; Vec&lt;u32&gt; {
       let mut r = vec![1];

       for p in 1..(number + 1) {
           if let Some(&amp;last) = r.last() {
               r.push((last * (number + 1 - p)) / p)
           }
       }
       r
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-28" id="填充相关-28"><h2>填充/相关</h2></a>
<a class="header" href="#scrabble-score" id="scrabble-score"><h1>Scrabble Score</h1></a>
<a class="header" href="#1-readme-29" id="1-readme-29"><h2>1. Readme</h2></a>
<a class="header" href="#拼字母的分数" id="拼字母的分数"><h1>拼字母的分数</h1></a>
<p>给出一个单词,计算该单词的字母的分数.</p>
<a class="header" href="#字母价值" id="字母价值"><h2>字母价值</h2></a>
<p>你需要这些:</p>
<pre><code class="language-text">26个英文字母                           对应有多少分
A, E, I, O, U, L, N, R, S, T       1
D, G                               2
B, C, M, P                         3
F, H, V, W, Y                      4
K                                  5
J, X                               8
Q, Z                               10
</code></pre>
<a class="header" href="#例子-3" id="例子-3"><h2>例子</h2></a>
<p>“cabbage”的得分值应为 14 分:</p>
<ul>
<li>C , 就得 3 分</li>
<li>A , 就得 1 分,两次</li>
<li>B , 就得 3 分,两次</li>
<li>G , 就得 2 分</li>
<li>E , 就得 1 分</li>
</ul>
<p>总计:</p>
<ul>
<li><code>3 + 2*1 + 2*3 + 2 + 1</code></li>
<li>= <code>3 + 2 + 6 + 3</code></li>
<li>= <code>5 + 9</code></li>
<li>= 14</li>
</ul>
<a class="header" href="#扩展-3" id="扩展-3"><h2>扩展</h2></a>
<ul>
<li>您可以玩，双重或三重字母.</li>
<li>你可以玩，一个双重或三个单词.</li>
</ul>
<a class="header" href="#资源-19" id="资源-19"><h2>资源</h2></a>
<p>受到 Extreme Startup 游戏的启发<a href="https://github.com/rchatley/extreme_startup">https://github.com/rchatley/extreme_startup</a></p>
<a class="header" href="#2-开始你的表演-29" id="2-开始你的表演-29"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">/// Compute the Scrabble score for a word.
pub fn score(word: &amp;str) -&gt; u64 {
   unimplemented!(&quot;Score {} in Scrabble.&quot;, word);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-29" id="3-测试代码查看-29"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn a_is_worth_one_point() {
   assert_eq!(score(&quot;a&quot;), 1);
}

#[test]
//#[ignore]
fn scoring_is_case_insensitive() {
   assert_eq!(score(&quot;A&quot;), 1);
}

#[test]
//#[ignore]
fn f_is_worth_four() {
   assert_eq!(score(&quot;f&quot;), 4);
}

#[test]
//#[ignore]
fn two_one_point_letters_make_a_two_point_word() {
   assert_eq!(score(&quot;at&quot;), 2);
}

#[test]
//#[ignore]
fn three_letter_word() {
   assert_eq!(score(&quot;zoo&quot;), 12);
}

#[test]
//#[ignore]
fn medium_word() {
   assert_eq!(score(&quot;street&quot;), 6);
}

#[test]
//#[ignore]
fn longer_words_with_valuable_letters() {
   assert_eq!(score(&quot;quirky&quot;), 22);
}

#[test]
//#[ignore]
fn long_mixed_case_word() {
   assert_eq!(score(&quot;OxyphenButazone&quot;), 41);
}

#[test]
//#[ignore]
fn non_english_scrabble_letters_do_not_score() {
   assert_eq!(score(&quot;pinata&quot;), 8, &quot;'n' should score 1&quot;);
   assert_eq!(score(&quot;piñata&quot;), 7, &quot;'ñ' should score 0&quot;);
}

#[test]
//#[ignore]
fn empty_words_are_worth_zero() {
   assert_eq!(score(&quot;&quot;), 0);
}

#[test]
//#[ignore]
fn all_letters_work() {
   assert_eq!(score(&quot;abcdefghijklmnopqrstuvwxyz&quot;), 87);
}

#[test]
//#[ignore]
fn german_letters_do_not_score() {
   assert_eq!(score(&quot;STRASSE&quot;), 7, &quot;\&quot;SS\&quot; should score 2&quot;);
   assert_eq!(score(&quot;STRAßE&quot;), 5, &quot;'ß' should score 0&quot;);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-29" id="4-答案-29"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;

pub fn score(word: &amp;str) -&gt; u16 {
   let values = dictionary();
   word.to_lowercase()
       .chars()
       .map(|c| values.get(&amp;c).clone())
       .fold(0, |score, v| score + v.unwrap_or(&amp;0))
}

fn dictionary() -&gt; HashMap&lt;char, u16&gt; {
   let mut values = HashMap::new();
   values.insert('a', 1);
   values.insert('b', 3);
   values.insert('c', 3);
   values.insert('d', 2);
   values.insert('e', 1);
   values.insert('f', 4);
   values.insert('g', 2);
   values.insert('h', 4);
   values.insert('i', 1);
   values.insert('j', 8);
   values.insert('k', 5);
   values.insert('l', 1);
   values.insert('m', 3);
   values.insert('n', 1);
   values.insert('o', 1);
   values.insert('p', 3);
   values.insert('q', 10);
   values.insert('r', 1);
   values.insert('s', 1);
   values.insert('t', 1);
   values.insert('u', 1);
   values.insert('v', 4);
   values.insert('w', 4);
   values.insert('x', 8);
   values.insert('y', 4);
   values.insert('z', 10);
   values
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-29" id="填充相关-29"><h2>填充/相关</h2></a>
<a class="header" href="#pangram" id="pangram"><h1>Pangram</h1></a>
<a class="header" href="#1-readme-30" id="1-readme-30"><h2>1. Readme</h2></a>
<a class="header" href="#全字母句pangram" id="全字母句pangram"><h1>全字母句（pangram）</h1></a>
<p>判断句子是否是全字母句。全字母句(希腊语:παγρμμα,pan 语法,”每个字母”)是一个使用字母表中每个字母，至少一次的句子。最著名的英语是 全字母句:</p>
<blockquote>
<p>The quick brown fox jumps over the lazy dog.</p>
</blockquote>
<p>字母表由 ASCII 字母<code>a</code>到<code>z</code>的全部组成，并且不区分大小写。输入不能包含非 ASCII 符号.</p>
<a class="header" href="#资源-20" id="资源-20"><h2>资源</h2></a>
<p>维基百科<a href="https://en.wikipedia.org/wiki/Pangram">https://en.wikipedia.org/wiki/Pangram</a></p>
<a class="header" href="#2-开始你的表演-30" id="2-开始你的表演-30"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">/// Determine whether a sentence is a pangram.
pub fn is_pangram(sentence: &amp;str) -&gt; bool {
   unimplemented!(&quot;Is {} a pangram?&quot;, sentence);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-30" id="3-测试代码查看-30"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn empty_strings_are_not_pangrams() {
   let sentence = &quot;&quot;;
   assert!(!is_pangram(&amp;sentence));
}

#[test]
//#[ignore]
fn classic_pangram_is_a_pangram() {
   let sentence = &quot;the quick brown fox jumps over the lazy dog&quot;;
   assert!(is_pangram(&amp;sentence));
}

#[test]
//#[ignore]
fn pangrams_must_have_all_letters() {
   let sentence = &quot;a quick movement of the enemy will jeopardize five gunboats&quot;;
   assert!(!is_pangram(&amp;sentence));
}

#[test]
//#[ignore]
fn pangrams_must_have_all_letters_two() {
   let sentence = &quot;the quick brown fish jumps over the lazy dog&quot;;
   assert!(!is_pangram(&amp;sentence));
}

#[test]
//#[ignore]
fn pangrams_must_include_z() {
   let sentence = &quot;the quick brown fox jumps over the lay dog&quot;;
   assert!(!is_pangram(&amp;sentence));
}

#[test]
//#[ignore]
fn underscores_do_not_affect_pangrams() {
   let sentence = &quot;the_quick_brown_fox_jumps_over_the_lazy_dog&quot;;
   assert!(is_pangram(&amp;sentence));
}

#[test]
//#[ignore]
fn numbers_do_not_affect_pangrams() {
   let sentence = &quot;the 1 quick brown fox jumps over the 2 lazy dogs&quot;;
   assert!(is_pangram(&amp;sentence));
}

#[test]
//#[ignore]
fn numbers_can_not_replace_letters() {
   let sentence = &quot;7h3 qu1ck brown fox jumps ov3r 7h3 lazy dog&quot;;
   assert!(!is_pangram(&amp;sentence));
}

#[test]
//#[ignore]
fn capitals_and_punctuation_can_be_in_pangrams() {
   let sentence = &quot;\&quot;Five quacking Zephyrs jolt my wax bed.\&quot;&quot;;
   assert!(is_pangram(&amp;sentence));
}

#[test]
//#[ignore]
fn non_ascii_characters_can_be_in_pangrams() {
   let sentence = &quot;Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich.&quot;;
   assert!(is_pangram(&amp;sentence));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-30" id="4-答案-30"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::BTreeSet;
use std::iter::FromIterator;

pub fn is_pangram(sentence: &amp;str) -&gt; bool {
   sentence
       .to_lowercase()
       .chars()
       .filter(|c| c.is_alphabetic())
       .filter(|c| c.is_ascii())
       .collect::&lt;BTreeSet&lt;char&gt;&gt;() == english_letter_set()
}

fn english_letter_set() -&gt; BTreeSet&lt;char&gt; {
   BTreeSet::from_iter(ENGLISH_ALPHABET.chars())
}

const ENGLISH_ALPHABET: &amp;'static str = &quot;abcdefghijklmnopqrstuvwxyz&quot;;

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-30" id="填充相关-30"><h2>填充/相关</h2></a>
<a class="header" href="#paasio" id="paasio"><h1>Paasio</h1></a>
<a class="header" href="#1-readme-31" id="1-readme-31"><h2>1. Readme</h2></a>
<a class="header" href="#paasio-1" id="paasio-1"><h1>Paasio</h1></a>
<p>报告网络 IO 统计.</p>
<p>你正在写一个<a href="http://en.wikipedia.org/wiki/Platform_as_a_service">PaaS</a>，你需要一种给网络和文件系统使用的帐单.</p>
<p>为报告 IO 统计信息的网络连接和文件，创建包装器。包装器必须报告:</p>
<ul>
<li>读取/写入的字节总数.</li>
<li>读取/写入操作的总数.</li>
</ul>
<a class="header" href="#网络和文件的抽象" id="网络和文件的抽象"><h2>网络和文件的抽象</h2></a>
<p>网络和文件操作，是实现了<a href="https://doc.rust-lang.org/std/io/trait.Read.html"><code>io::Read</code></a>和<a href="https://doc.rust-lang.org/std/io/trait.Write.html"><code>io::Write</code></a> <code>traits</code> 的。因此,有必要为您的类型实现这些特性.</p>
<a class="header" href="#资源-21" id="资源-21"><h2>资源</h2></a>
<p>布瑞恩松岛<a href="https://github.com/bmatsuo">https://github.com/bmatsuo</a></p>
<a class="header" href="#2-开始你的表演-31" id="2-开始你的表演-31"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::io::{Read, Result, Write};

pub struct ReadStats&lt;R&gt;(::std::marker::PhantomData&lt;R&gt;);

impl&lt;R: Read&gt; ReadStats&lt;R&gt; {
   // _wrapped is ignored because R is not bounded on Debug or Display and therefore
   // can't be passed through format!(). For actual implementation you will likely
   // wish to remove the leading underscore so the variable is not ignored.
   pub fn new(_wrapped: R) -&gt; ReadStats&lt;R&gt; {
       unimplemented!()
   }

   pub fn get_ref(&amp;self) -&gt; &amp;R {
       unimplemented!()
   }

   pub fn bytes_through(&amp;self) -&gt; usize {
       unimplemented!()
   }

   pub fn reads(&amp;self) -&gt; usize {
       unimplemented!()
   }
}

impl&lt;R: Read&gt; Read for ReadStats&lt;R&gt; {
   fn read(&amp;mut self, buf: &amp;mut [u8]) -&gt; Result&lt;usize&gt; {
       unimplemented!(&quot;Collect statistics about this call reading {:?}&quot;, buf)
   }
}

pub struct WriteStats&lt;W&gt;(::std::marker::PhantomData&lt;W&gt;);

impl&lt;W: Write&gt; WriteStats&lt;W&gt; {
   // _wrapped is ignored because W is not bounded on Debug or Display and therefore
   // can't be passed through format!(). For actual implementation you will likely
   // wish to remove the leading underscore so the variable is not ignored.
   pub fn new(_wrapped: W) -&gt; WriteStats&lt;W&gt; {
       unimplemented!()
   }

   pub fn get_ref(&amp;self) -&gt; &amp;W {
       unimplemented!()
   }

   pub fn bytes_through(&amp;self) -&gt; usize {
       unimplemented!()
   }

   pub fn writes(&amp;self) -&gt; usize {
       unimplemented!()
   }
}

impl&lt;W: Write&gt; Write for WriteStats&lt;W&gt; {
   fn write(&amp;mut self, buf: &amp;[u8]) -&gt; Result&lt;usize&gt; {
       unimplemented!(&quot;Collect statistics about this call writing {:?}&quot;, buf)
   }

   fn flush(&amp;mut self) -&gt; Result&lt;()&gt; {
       unimplemented!()
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-31" id="3-测试代码查看-31"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
/// test a few read scenarios
macro_rules! test_read {
   ($(#[$attr:meta])* $modname:ident ($input:expr, $len:expr)) =&gt; {
       mod $modname {
           use std::io::{Read, BufReader};


           const CHUNK_SIZE: usize = 2;

           $(#[$attr])*
           #[test]
           fn test_read_passthrough() {
               let data = $input;
               let size = $len(&amp;data);
               let mut reader = ReadStats::new(data);

               let mut buffer = Vec::with_capacity(size);
               let qty_read = reader.read_to_end(&amp;mut buffer);

               assert!(qty_read.is_ok());
               assert_eq!(size, qty_read.unwrap());
               assert_eq!(size, buffer.len());
               // 2: first to read all the data, second to check that
               // there wasn't any more pending data which simply didn't
               // fit into the existing buffer
               assert_eq!(2, reader.reads());
               assert_eq!(size, reader.bytes_through());
           }

           $(#[$attr])*
           #[test]
           fn test_read_chunks() {
               let data = $input;
               let size = $len(&amp;data);
               let mut reader = ReadStats::new(data);

               let mut buffer = [0_u8; CHUNK_SIZE];
               let mut chunks_read = 0;
               while reader.read(&amp;mut buffer[..]).unwrap_or_else(|_| panic!(&quot;read failed at chunk {}&quot;, chunks_read+1)) &gt; 0 {
                   chunks_read += 1;
               }

               assert_eq!(size / CHUNK_SIZE, chunks_read);
               // we read once more than the number of chunks, because the final
               // read returns 0 new bytes
               assert_eq!(1+chunks_read, reader.reads());
               assert_eq!(size, reader.bytes_through());
           }

           $(#[$attr])*
           #[test]
           fn test_read_buffered_chunks() {
               let data = $input;
               let size = $len(&amp;data);
               let mut reader = BufReader::new(ReadStats::new(data));

               let mut buffer = [0_u8; CHUNK_SIZE];
               let mut chunks_read = 0;
               while reader.read(&amp;mut buffer[..]).unwrap_or_else(|_| panic!(&quot;read failed at chunk {}&quot;, chunks_read+1)) &gt; 0 {
                   chunks_read += 1;
               }

               assert_eq!(size / CHUNK_SIZE, chunks_read);
               // the BufReader should smooth out the reads, collecting into
               // a buffer and performing only two read operations:
               // the first collects everything into the buffer,
               // and the second ensures that no data remains
               assert_eq!(2, reader.get_ref().reads());
               assert_eq!(size, reader.get_ref().bytes_through());
           }
       }
   };
}

/// test a few write scenarios
macro_rules! test_write {
   ($(#[$attr:meta])* $modname:ident ($input:expr, $len:expr)) =&gt; {
       mod $modname {
           use std::io::{self, Write, BufWriter};


           const CHUNK_SIZE: usize = 2;
           $(#[$attr])*
           #[test]
           fn test_write_passthrough() {
               let data = $input;
               let size = $len(&amp;data);
               let mut writer = WriteStats::new(Vec::with_capacity(size));
               let written = writer.write(data);
               assert!(written.is_ok());
               assert_eq!(size, written.unwrap());
               assert_eq!(size, writer.bytes_through());
               assert_eq!(1, writer.writes());
               assert_eq!(data, writer.get_ref().as_slice());
           }

           $(#[$attr])*
           #[test]
           fn test_sink_oneshot() {
               let data = $input;
               let size = $len(&amp;data);
               let mut writer = WriteStats::new(io::sink());
               let written = writer.write(data);
               assert!(written.is_ok());
               assert_eq!(size, written.unwrap());
               assert_eq!(size, writer.bytes_through());
               assert_eq!(1, writer.writes());
           }

           $(#[$attr])*
           #[test]
           fn test_sink_windowed() {
               let data = $input;
               let size = $len(&amp;data);
               let mut writer = WriteStats::new(io::sink());

               let mut chunk_count = 0;
               for chunk in data.chunks(CHUNK_SIZE) {
                   chunk_count += 1;
                   let written = writer.write(chunk);
                   assert!(written.is_ok());
                   assert_eq!(CHUNK_SIZE, written.unwrap());
               }
               assert_eq!(size, writer.bytes_through());
               assert_eq!(chunk_count, writer.writes());
           }

           $(#[$attr])*
           #[test]
           fn test_sink_buffered_windowed() {
               let data = $input;
               let size = $len(&amp;data);
               let mut writer = BufWriter::new(WriteStats::new(io::sink()));

               for chunk in data.chunks(CHUNK_SIZE) {
                   let written = writer.write(chunk);
                   assert!(written.is_ok());
                   assert_eq!(CHUNK_SIZE, written.unwrap());
               }
               // at this point, nothing should have yet been passed through to
               // our writer
               assert_eq!(0, writer.get_ref().bytes_through());
               assert_eq!(0, writer.get_ref().writes());

               // after flushing, everything should pass through in one go
               assert!(writer.flush().is_ok());
               assert_eq!(size, writer.get_ref().bytes_through());
               assert_eq!(1, writer.get_ref().writes());
           }
       }
   };
}

#[test]
fn test_create_stats() {
   let mut data: Vec&lt;u8&gt; = Vec::new();
   let _ = ReadStats::new(data.as_slice());
   let _ = WriteStats::new(data.as_mut_slice());
}

test_read!( read_string (
   &quot;Twas brillig, and the slithy toves/Did gyre and gimble in the wabe:/All mimsy were the borogoves,/And the mome raths outgrabe.&quot;.as_bytes(),
   |d: &amp;[u8]| d.len()
));
test_write!( write_string (
   &quot;Beware the Jabberwock, my son!/The jaws that bite, the claws that catch!/Beware the Jubjub bird, and shun/The frumious Bandersnatch!&quot;.as_bytes(),
   |d: &amp;[u8]| d.len()
));

test_read!(read_byte_literal(
   &amp;[1_u8, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144][..],
   |d: &amp;[u8]| d.len()
));
test_write!(write_byte_literal(
   &amp;[2_u8, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,][..],
   |d: &amp;[u8]| d.len()
));

test_read!(read_file(
   ::std::fs::File::open(&quot;README.md&quot;).expect(&quot;readme must be present&quot;),
   |f: &amp;::std::fs::File| f.metadata().expect(&quot;metadata must be present&quot;).len() as usize
));

#[test]
fn read_stats_by_ref_returns_wrapped_reader() {
   use ReadStats;

   let input =
       &quot;Why, sometimes I've believed as many as six impossible things before breakfast&quot;.as_bytes();
   let reader = ReadStats::new(input);
   assert_eq!(reader.get_ref(), &amp;input);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-31" id="4-答案-31"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::io::{Read, Result, Write};

pub struct WriteStats&lt;W: Write&gt; {
   inner: W,
   bytes: usize,
   writes: usize,
}

impl&lt;W: Write&gt; WriteStats&lt;W&gt; {
   pub fn new(wrapped: W) -&gt; WriteStats&lt;W&gt; {
       WriteStats {
           inner: wrapped,
           bytes: 0,
           writes: 0,
       }
   }

   pub fn get_ref(&amp;self) -&gt; &amp;W {
       &amp;self.inner
   }

   pub fn bytes_through(&amp;self) -&gt; usize {
       self.bytes
   }

   pub fn writes(&amp;self) -&gt; usize {
       self.writes
   }
}

impl&lt;W: Write&gt; Write for WriteStats&lt;W&gt; {
   fn write(&amp;mut self, buf: &amp;[u8]) -&gt; Result&lt;usize&gt; {
       self.writes += 1;
       let written = self.inner.write(buf)?;
       self.bytes += written;
       Ok(written)
   }

   fn flush(&amp;mut self) -&gt; Result&lt;()&gt; {
       self.inner.flush()
   }
}

pub struct ReadStats&lt;R: Read&gt; {
   inner: R,
   bytes: usize,
   reads: usize,
}

impl&lt;R: Read&gt; ReadStats&lt;R&gt; {
   pub fn new(wrapped: R) -&gt; ReadStats&lt;R&gt; {
       ReadStats {
           inner: wrapped,
           bytes: 0,
           reads: 0,
       }
   }

   pub fn get_ref(&amp;self) -&gt; &amp;R {
       &amp;self.inner
   }

   pub fn bytes_through(&amp;self) -&gt; usize {
       self.bytes
   }

   pub fn reads(&amp;self) -&gt; usize {
       self.reads
   }
}

impl&lt;R: Read&gt; Read for ReadStats&lt;R&gt; {
   fn read(&amp;mut self, buf: &amp;mut [u8]) -&gt; Result&lt;usize&gt; {
       self.reads += 1;
       let read = self.inner.read(buf)?;
       self.bytes += read;
       Ok(read)
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-31" id="填充相关-31"><h2>填充/相关</h2></a>
<a class="header" href="#nucleotide-count" id="nucleotide-count"><h1>Nucleotide Count</h1></a>
<a class="header" href="#1-readme-32" id="1-readme-32"><h2>1. Readme</h2></a>
<a class="header" href="#核苷酸nucleotide计数" id="核苷酸nucleotide计数"><h1>核苷酸(Nucleotide)计数</h1></a>
<p>给定一条单 DNA 链 ,计算每个核苷酸在字符串中出现的次数.</p>
<p>地球上每一生物的遗传语言都是 DNA.DNA 是一种大分子,它是由一系列叫做核苷酸的单个元素组成。DNA 中存在 4 种类型,它们仅略有不同,并且可用以下符号表示:’A’表示腺嘌呤,’C’表示胞嘧啶,’G’表示鸟嘌呤,’T’表示胸腺嘧啶.</p>
<p>下面是一个类比:</p>
<ul>
<li>树枝组成鸟的巢</li>
<li>核苷酸组成 DNA 链</li>
</ul>
<a class="header" href="#资源-22" id="资源-22"><h2>资源</h2></a>
<p>罗瑟琳 DNA 核苷酸问题的计算<a href="http://rosalind.info/problems/dna/">http://rosalind.info/problems/dna/</a></p>
<a class="header" href="#2-开始你的表演-32" id="2-开始你的表演-32"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::collections::HashMap;

pub fn count(nucleotide: char, dna: &amp;str) -&gt; Result&lt;usize, char&gt; {
   unimplemented!(
       &quot;How much of nucleotide type '{}' is contained inside DNA string '{}'?&quot;,
       nucleotide,
       dna
   );
}

pub fn nucleotide_counts(dna: &amp;str) -&gt; Result&lt;HashMap&lt;char, usize&gt;, char&gt; {
   unimplemented!(
       &quot;How much of every nucleotide type is contained inside DNA string '{}'?&quot;,
       dna
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-32" id="3-测试代码查看-32"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// use std::collections::HashMap;

fn check_dna(s: &amp;str, pairs: &amp;[(char, usize)]) {
   // The reason for the awkward code in here is to ensure that the failure
   // message for assert_eq! is as informative as possible. A simpler
   // solution would simply check the length of the map, and then
   // check for the presence and value of each key in the given pairs vector.
   let mut m: HashMap&lt;char, usize&gt; = nucleotide_counts(s).unwrap();
   for &amp;(k, v) in pairs.iter() {
       assert_eq!((k, m.remove(&amp;k)), (k, Some(v)));
   }
   // may fail with a message that clearly shows all extra pairs in the map
   assert_eq!(m.iter().collect::&lt;Vec&lt;(&amp;char, &amp;usize)&gt;&gt;(), vec![]);
}

#[test]
fn count_returns_result() {
   assert!(count('A', &quot;&quot;).is_ok());
}

#[test]
//#[ignore]
fn test_count_empty() {
   assert_eq!(count('A', &quot;&quot;), Ok(0));
}

#[test]
//#[ignore]
fn count_invalid_nucleotide() {
   assert_eq!(count('X', &quot;A&quot;), Err('X'));
}

#[test]
//#[ignore]
fn count_invalid_dna() {
   assert_eq!(count('A', &quot;AX&quot;), Err('X'));
}

#[test]
//#[ignore]
fn test_count_repetitive_cytosine() {
   assert_eq!(count('C', &quot;CCCCC&quot;), Ok(5));
}

#[test]
//#[ignore]
fn test_count_only_thymine() {
   assert_eq!(count('T', &quot;GGGGGTAACCCGG&quot;), Ok(1));
}

#[test]
//#[ignore]
fn counts_returns_result() {
   assert!(nucleotide_counts(&quot;ACGT&quot;).is_ok());
}

#[test]
//#[ignore]
fn test_nucleotide_count_empty() {
   check_dna(&quot;&quot;, &amp;[('A', 0), ('T', 0), ('C', 0), ('G', 0)]);
}

#[test]
//#[ignore]
fn test_nucleotide_count_only_guanine() {
   check_dna(&quot;GGGGGGGG&quot;, &amp;[('A', 0), ('T', 0), ('C', 0), ('G', 8)]);
}

#[test]
//#[ignore]
fn test_nucleotide_count_counts_all() {
   check_dna(
       &quot;AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAA\
        GAGTGTCTGATAGCAGC&quot;,
       &amp;[('A', 20), ('T', 21), ('C', 12), ('G', 17)],
   );
}

#[test]
//#[ignore]
fn counts_invalid_nucleotide_results_in_err() {
   assert_eq!(nucleotide_counts(&quot;GGXXX&quot;), Err('X'));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-32" id="4-答案-32"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;

static VALID_NUCLEOTIDES: &amp;'static str = &quot;ACGT&quot;;

fn valid(c: char) -&gt; Result&lt;char, char&gt; {
   if VALID_NUCLEOTIDES.contains(c) {
       Ok(c)
   } else {
       Err(c)
   }
}

pub fn count(nucleotide: char, input: &amp;str) -&gt; Result&lt;usize, char&gt; {
   valid(nucleotide)?;
   let mut count = 0;
   for c in input.chars() {
       if valid(c)? == nucleotide {
           count += 1;
       }
   }
   Ok(count)
}

pub fn nucleotide_counts(input: &amp;str) -&gt; Result&lt;HashMap&lt;char, usize&gt;, char&gt; {
   let mut map: HashMap&lt;char, usize&gt; = VALID_NUCLEOTIDES.chars().map(|c| (c, 0)).collect();
   for nucleotide in input.chars() {
       if let Some(n) = map.get_mut(&amp;nucleotide) {
           *n += 1;
       } else {
           return Err(nucleotide);
       }
   }
   Ok(map)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-32" id="填充相关-32"><h2>填充/相关</h2></a>
<a class="header" href="#luhn" id="luhn"><h1>Luhn</h1></a>
<a class="header" href="#1-readme-33" id="1-readme-33"><h2>1. Readme</h2></a>
<a class="header" href="#luhn-1" id="luhn-1"><h1>Luhn</h1></a>
<p>给定一个数,判定它是否有效 Luhn 公式.</p>
<blockquote>
<p>Luhn 算法，也称为“模 10”算法</p>
</blockquote>
<p>这个<a href="https://en.wikipedia.org/wiki/Luhn_algorithm">Luhn 算法</a>是一个简单的校验和公式,用于验证各种身份号码,如信用卡号码和加拿大社会保险号码.</p>
<p>任务是检查给定字符串是否有效.</p>
<a class="header" href="#验证一个数" id="验证一个数"><h2>验证一个数</h2></a>
<p>长度为 1 或更小的字符串无效。在输入中允许使用空格，但在检查前，应清除空格。所有其他非数字字符都是不允许的.</p>
<a class="header" href="#例子-1有效信用卡号码" id="例子-1有效信用卡号码"><h2>例子 1:有效信用卡号码</h2></a>
<pre><code class="language-text">4539 1488 0343 6467
</code></pre>
<p>LuHN 算法的第一步是，从<strong>右边</strong>开始每第二个数字加倍。我们要加倍的位</p>
<pre><code class="language-text">4_3_ 1_8_ 0_4_ 6_6_
</code></pre>
<p>如果加倍的数字值导致大于 9 的数字,则将此值减去 9。我们加倍的结果:</p>
<pre><code class="language-text">8569 2478 0383 3437
</code></pre>
<blockquote>
<p><code>1_8_ =&gt; 2_7_</code> , <code>8*2 - 9 = 7</code></p>
</blockquote>
<p>然后把所有数字加起来:</p>
<pre><code class="language-text">8+5+6+9+2+4+7+8+0+3+8+3+3+4+3+7 = 80
</code></pre>
<p>如果总和可被 10 整除,则数字是有效的.这个号码是有效的!</p>
<a class="header" href="#例子-2信用卡号码无效" id="例子-2信用卡号码无效"><h2>例子 2:信用卡号码无效</h2></a>
<pre><code class="language-text">8273 1232 7352 0569
</code></pre>
<p>把每第二个数字加倍,从右边开始</p>
<pre><code class="language-text">7253 2262 5312 0539
</code></pre>
<p>合计数字</p>
<pre><code class="language-text">7+2+5+3+2+2+6+2+5+3+1+2+0+5+3+9 = 57
</code></pre>
<p>57 不能被 10 整除,所以这个数字是无效的.</p>
<a class="header" href="#资源-23" id="资源-23"><h2>资源</h2></a>
<p>维基百科上的 LuHn 算法<a href="http://en.wikipedia.org/wiki/Luhn_algorithm">http://en.wikipedia.org/wiki/Luhn_algorithm</a></p>
<a class="header" href="#2-开始你的表演-33" id="2-开始你的表演-33"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">/// Check a Luhn checksum.
pub fn is_valid(code: &amp;str) -&gt; bool {
   unimplemented!(&quot;Is the Luhn checksum for {} valid?&quot;, code);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-33" id="3-测试代码查看-33"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn single_digit_string_is_invalid() {
   assert!(!is_valid(&quot;1&quot;));
}

#[test]
//#[ignore]
fn single_zero_string_is_invalid() {
   assert!(!is_valid(&quot;0&quot;));
}

#[test]
//#[ignore]
fn simple_valid_sin() {
   assert!(is_valid(&quot; 5 9 &quot;));
}

#[test]
//#[ignore]
fn valid_canadian_sin_is_valid() {
   assert!(is_valid(&quot;046 454 286&quot;));
}

#[test]
//#[ignore]
fn invalid_canadian_sin_is_invalid() {
   assert!(!is_valid(&quot;046 454 287&quot;));
}

#[test]
//#[ignore]
fn invalid_credit_card_is_invalid() {
   assert!(!is_valid(&quot;8273 1232 7352 0569&quot;));
}

#[test]
//#[ignore]
fn strings_that_contain_non_digits_are_invalid() {
   assert!(!is_valid(&quot;046a 454 286&quot;));
}

#[test]
//#[ignore]
fn punctuation_is_invalid() {
   assert!(!is_valid(&quot;055-444-285&quot;));
}

#[test]
//#[ignore]
fn symbols_are_invalid() {
   assert!(!is_valid(&quot;055£ 444$ 285&quot;));
}

#[test]
//#[ignore]
fn single_digit_with_space_is_invalid() {
   assert!(!is_valid(&quot; 0&quot;));
}

#[test]
//#[ignore]
fn lots_of_zeros_are_valid() {
   assert!(is_valid(&quot; 00000&quot;));
}

#[test]
//#[ignore]
fn another_valid_sin() {
   assert!(is_valid(&quot;055 444 285&quot;));
}

#[test]
//#[ignore]
fn nine_doubled_is_nine() {
   assert!(is_valid(&quot;091&quot;));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-33" id="4-答案-33"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn is_valid(candidate: &amp;str) -&gt; bool {
   if candidate.chars().filter(|c| c.is_digit(10)).take(2).count() &lt;= 1
       || candidate.chars().any(|c| !c.is_digit(10) &amp;&amp; c != ' ')
   {
       return false;
   }

   candidate
       .chars()
       .filter_map(|c| c.to_digit(10))
       .rev()
       .enumerate()
       .map(|(index, digit)| if index % 2 == 0 { digit } else { digit * 2 })
       .map(|digit| if digit &gt; 9 { digit - 9 } else { digit })
       .sum::&lt;u32&gt;() % 10 == 0
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-33" id="填充相关-33"><h2>填充/相关</h2></a>
<a class="header" href="#largest-series-product" id="largest-series-product"><h1>Largest Series Product</h1></a>
<a class="header" href="#1-readme-34" id="1-readme-34"><h2>1. Readme</h2></a>
<a class="header" href="#最大系列乘积" id="最大系列乘积"><h1>最大系列乘积</h1></a>
<p>给定一个数字串,计算长度为 n 的连续子串的最大乘积.</p>
<p>例如,对于输入<code>'1027839564'</code> ， 3 位数系列的最大乘积是 270 (<code>9 * 5 * 6</code>), 5 位数系列的最大乘积为 7560 (<code>7 * 8 * 3 * 9 * 5</code>).</p>
<p>注意这些系列数字字符，在输入中，只要求<em>相邻位置</em>，不需要<em>连续数值(123456..)</em>.</p>
<p>对于输入<code>'73167176531330624919225119674426574742355349194934'</code>一系列 6 位数的最大乘积是 23520.</p>
<a class="header" href="#rust-的最大系列乘积" id="rust-的最大系列乘积"><h1>Rust 的最大系列乘积</h1></a>
<p>这些迭代器可能是有用的,取决于您的方法.</p>
<ul>
<li><a href="https://doc.rust-lang.org/std/primitive.slice.html#method.windows">Windows</a></li>
<li><a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.product">Product</a></li>
</ul>
<a class="header" href="#资源-24" id="资源-24"><h2>资源</h2></a>
<p>欧拉工程的问题 8 的一个变种<a href="http://projecteuler.net/problem=8">http://projecteuler.net/problem=8</a></p>
<a class="header" href="#2-开始你的表演-34" id="2-开始你的表演-34"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">#[derive(Debug, PartialEq)]
pub enum Error {
   SpanTooLong,
   InvalidDigit(char),
}

pub fn lsp(string_digits: &amp;str, span: usize) -&gt; Result&lt;u64, Error&gt; {
   unimplemented!(
       &quot;largest series product of a span of {} digits in {}&quot;,
       span,
       string_digits
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-34" id="3-测试代码查看-34"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn return_is_a_result() {
   assert!(lsp(&quot;29&quot;, 2).is_ok());
}

#[test]
//#[ignore]
fn find_the_largest_product_when_span_equals_length() {
   assert_eq!(Ok(18), lsp(&quot;29&quot;, 2));
}

#[test]
//#[ignore]
fn find_the_largest_product_of_two_with_numbers_in_order() {
   assert_eq!(Ok(72), lsp(&quot;0123456789&quot;, 2));
}

#[test]
//#[ignore]
fn find_the_largest_product_of_two_with_numbers_not_in_order() {
   assert_eq!(Ok(48), lsp(&quot;576802143&quot;, 2));
}

#[test]
//#[ignore]
fn find_the_largest_product_of_three_with_numbers_in_order() {
   assert_eq!(Ok(504), lsp(&quot;0123456789&quot;, 3));
}

#[test]
//#[ignore]
fn find_the_largest_product_of_three_with_numbers_not_in_order() {
   assert_eq!(Ok(270), lsp(&quot;1027839564&quot;, 3));
}

#[test]
//#[ignore]
fn find_the_largest_product_of_five_with_numbers_in_order() {
   assert_eq!(Ok(15120), lsp(&quot;0123456789&quot;, 5));
}

#[test]
//#[ignore]
fn span_of_six_in_a_large_number() {
   assert_eq!(
       Ok(23520),
       lsp(&quot;73167176531330624919225119674426574742355349194934&quot;, 6)
   );
}

#[test]
//#[ignore]
fn returns_zero_if_number_is_zeros() {
   assert_eq!(Ok(0), lsp(&quot;0000&quot;, 2));
}

#[test]
//#[ignore]
fn returns_zero_if_all_products_are_zero() {
   assert_eq!(Ok(0), lsp(&quot;99099&quot;, 3));
}

#[test]
//#[ignore]
fn a_span_is_longer_than_number_is_an_error() {
   assert_eq!(Err(Error::SpanTooLong), lsp(&quot;123&quot;, 4));
}

// There may be some confusion about whether this should be 1 or error.
// The reasoning for it being 1 is this:
// There is one 0-character string contained in the empty string.
// That's the empty string itself.
// The empty product is 1 (the identity for multiplication).
// Therefore LSP('', 0) is 1.
// It's NOT the case that LSP('', 0) takes max of an empty list.
// So there is no error.
// Compare against LSP('123', 4):
// There are zero 4-character strings in '123'.
// So LSP('123', 4) really DOES take the max of an empty list.
// So LSP('123', 4) errors and LSP('', 0) does NOT.
#[test]
//#[ignore]
fn an_empty_string_and_no_span_returns_one() {
   assert_eq!(Ok(1), lsp(&quot;&quot;, 0));
}

#[test]
//#[ignore]
fn a_non_empty_string_and_no_span_returns_one() {
   assert_eq!(Ok(1), lsp(&quot;123&quot;, 0));
}

#[test]
//#[ignore]
fn empty_string_and_non_zero_span_is_an_error() {
   assert_eq!(Err(Error::SpanTooLong), lsp(&quot;&quot;, 1));
}

#[test]
//#[ignore]
fn a_string_with_non_digits_is_an_error() {
   assert_eq!(Err(Error::InvalidDigit('a')), lsp(&quot;1234a5&quot;, 2));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-34" id="4-答案-34"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[derive(Debug, PartialEq)]
pub enum Error {
   SpanTooLong,
   InvalidDigit(char),
}

pub fn lsp(string_digits: &amp;str, span: usize) -&gt; Result&lt;u64, Error&gt; {
   if span == 0 {
       return Ok(1);
   }

   if let Some(invalid) = string_digits.chars().find(|c| !c.is_digit(10)) {
       return Err(Error::InvalidDigit(invalid));
   }

   let products: Vec&lt;u64&gt; = string_digits
       .chars()
       .map(|c| c.to_digit(10).unwrap() as u64)
       .collect::&lt;Vec&lt;u64&gt;&gt;()
       .windows(span)
       .map(|w| w.into_iter().product())
       .collect();

   if let Some(&amp;x) = products.iter().max() {
       Ok(x)
   } else {
       Err(Error::SpanTooLong)
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-34" id="填充相关-34"><h2>填充/相关</h2></a>
<a class="header" href="#word-count" id="word-count"><h1>Word Count</h1></a>
<a class="header" href="#1-readme-35" id="1-readme-35"><h2>1. Readme</h2></a>
<a class="header" href="#字数" id="字数"><h1>字数</h1></a>
<p>给定一个短语,计算该短语中，每个单词的出现次数.</p>
<p>例如输入<code>&quot;olly olly in come free&quot;</code></p>
<pre><code class="language-text">olly: 2
in: 1
come: 1
free: 1
</code></pre>
<a class="header" href="#资源-25" id="资源-25"><h2>资源</h2></a>
<p>这是一个经典的玩具问题,但我们通过在 Go Tour 中，看到它，才想起提醒.</p>
<a class="header" href="#2-开始你的表演-35" id="2-开始你的表演-35"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::collections::HashMap;

/// Count occurrences of words.
pub fn word_count(words: &amp;str) -&gt; HashMap&lt;String, u32&gt; {
   unimplemented!(&quot;Count of occurrences of words in {:?}&quot;, words);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-35" id="3-测试代码查看-35"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// use std::collections::HashMap;

fn check_word_count(s: &amp;str, pairs: &amp;[(&amp;str, u32)]) {
   // The reason for the awkward code in here is to ensure that the failure
   // message for assert_eq! is as informative as possible. A simpler
   // solution would simply check the length of the map, and then
   // check for the presence and value of each key in the given pairs vector.
   let mut m: HashMap&lt;String, u32&gt; = word_count(s);
   for &amp;(k, v) in pairs.iter() {
       assert_eq!((k, m.remove(&amp;k.to_string()).unwrap_or(0)), (k, v));
   }
   // may fail with a message that clearly shows all extra pairs in the map
   assert_eq!(m.iter().collect::&lt;Vec&lt;(&amp;String, &amp;u32)&gt;&gt;(), vec![]);
}

#[test]
fn test_count_one_word() {
   check_word_count(&quot;word&quot;, &amp;[(&quot;word&quot;, 1)]);
}

#[test]
//#[ignore]
fn test_count_one_of_each() {
   check_word_count(&quot;one of each&quot;, &amp;[(&quot;one&quot;, 1), (&quot;of&quot;, 1), (&quot;each&quot;, 1)]);
}

#[test]
//#[ignore]
fn test_count_multiple_occurrences() {
   check_word_count(
       &quot;one fish two fish red fish blue fish&quot;,
       &amp;[(&quot;one&quot;, 1), (&quot;fish&quot;, 4), (&quot;two&quot;, 1), (&quot;red&quot;, 1), (&quot;blue&quot;, 1)],
   );
}

#[test]
//#[ignore]
fn test_ignore_punctuation() {
   check_word_count(
       &quot;car : carpet as java : javascript!!&amp;@$%^&amp;&quot;,
       &amp;[
           (&quot;car&quot;, 1),
           (&quot;carpet&quot;, 1),
           (&quot;as&quot;, 1),
           (&quot;java&quot;, 1),
           (&quot;javascript&quot;, 1),
       ],
   );
}

#[test]
//#[ignore]
fn test_include_numbers() {
   check_word_count(
       &quot;testing, 1, 2 testing&quot;,
       &amp;[(&quot;testing&quot;, 2), (&quot;1&quot;, 1), (&quot;2&quot;, 1)],
   );
}

#[test]
//#[ignore]
fn test_normalize_case() {
   check_word_count(&quot;go Go GO Stop stop&quot;, &amp;[(&quot;go&quot;, 3), (&quot;stop&quot;, 2)]);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-35" id="4-答案-35"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;

pub fn word_count(input: &amp;str) -&gt; HashMap&lt;String, u32&gt; {
   let mut map: HashMap&lt;String, u32&gt; = HashMap::new();
   let lower = input.to_lowercase();
   let slice: &amp;str = lower.as_ref();
   for word in slice
       .split(|c: char| !c.is_alphanumeric())
       .filter(|s| !s.is_empty())
   {
       *map.entry(word.to_string()).or_insert(0) += 1;
   }
   map
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-35" id="填充相关-35"><h2>填充/相关</h2></a>
<a class="header" href="#atbash-cipher" id="atbash-cipher"><h1>Atbash Cipher</h1></a>
<a class="header" href="#1-readme-36" id="1-readme-36"><h2>1. Readme</h2></a>
<a class="header" href="#atbash-cipher-1" id="atbash-cipher-1"><h1>Atbash Cipher</h1></a>
<p>创建 Atbash 密码的实现,这是在中东创建的古老加密系统.</p>
<p>Atbash 密码是一种简单的替换密码,它依赖于转置字母表中的所有字母,使得生成的字母表向后。</p>
<ul>
<li>第一个字母替换为最后一个字母,</li>
<li>第二个字母替换为倒数第二个字母,</li>
<li>依此类推.</li>
</ul>
<p>拉丁字母的 Atbash 密码如下:</p>
<pre><code class="language-text">明文:  abcdefghijklmnopqrstuvwxyz
加密:  zyxwvutsrqponmlkjihgfedcba
</code></pre>
<p>它是一个非常弱的加密方式，因为它只有一个加密可能性，且为一个简单的单字母替换密码。但是,这并不是现在’加密游戏-练习时间’的问题.</p>
<p>密文以固定长度的组写出，传统的组大小为 5 个字母，并且不包括标点符号。这是为了使单词边界，更难猜测。</p>
<a class="header" href="#例子-4" id="例子-4"><h2>例子</h2></a>
<ul>
<li><code>test</code>，编码为<code>gvhg</code></li>
<li><code>gvhg</code>，解码为<code>test</code></li>
<li><code>gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt</code>解码为<code>thequickbrownfoxjumpsoverthelazydog</code></li>
</ul>
<a class="header" href="#资源-26" id="资源-26"><h2>资源</h2></a>
<p>维基百科<a href="http://en.wikipedia.org/wiki/Atbash">http://en.wikipedia.org/wiki/Atbash</a></p>
<a class="header" href="#2-开始你的表演-36" id="2-开始你的表演-36"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">/// &quot;Encipher&quot; with the Atbash cipher.
pub fn encode(plain: &amp;str) -&gt; String {
   unimplemented!(&quot;Encoding of {:?} in Atbash cipher.&quot;, plain);
}

/// &quot;Decipher&quot; with the Atbash cipher.
pub fn decode(cipher: &amp;str) -&gt; String {
   unimplemented!(&quot;Decoding of {:?} in Atbash cipher.&quot;, cipher);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-36" id="3-测试代码查看-36"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_encode_yes() {
   assert_eq!(&quot;bvh&quot;, encode(&quot;yes&quot;));
}

#[test]
//#[ignore]
fn test_encode_no() {
   assert_eq!(&quot;ml&quot;, encode(&quot;no&quot;));
}

#[test]
//#[ignore]
fn test_encode_omg() {
   assert_eq!(&quot;lnt&quot;, encode(&quot;OMG&quot;));
}

#[test]
//#[ignore]
fn test_encode_spaces() {
   assert_eq!(&quot;lnt&quot;, encode(&quot;O M G&quot;));
}

#[test]
//#[ignore]
fn test_encode_mindblowingly() {
   assert_eq!(&quot;nrmwy oldrm tob&quot;, encode(&quot;mindblowingly&quot;));
}

#[test]
//#[ignore]
fn test_encode_numbers() {
   assert_eq!(&quot;gvhgr mt123 gvhgr mt&quot;, encode(&quot;Testing,1 2 3, testing.&quot;));
}

#[test]
//#[ignore]
fn test_encode_deep_thought() {
   assert_eq!(&quot;gifgs rhurx grlm&quot;, encode(&quot;Truth is fiction.&quot;));
}

#[test]
//#[ignore]
fn test_encode_all_the_letters() {
   assert_eq!(
       &quot;gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt&quot;,
       encode(&quot;The quick brown fox jumps over the lazy dog.&quot;)
   );
}

#[test]
//#[ignore]
fn test_encode_ignores_non_ascii() {
   assert_eq!(&quot;mlmzh xrrrt mlivw&quot;, encode(&quot;non ascii éignored&quot;));
}

#[test]
//#[ignore]
fn test_decode_exercism() {
   assert_eq!(&quot;exercism&quot;, decode(&quot;vcvix rhn&quot;));
}

#[test]
//#[ignore]
fn test_decode_a_sentence() {
   assert_eq!(
       &quot;anobstacleisoftenasteppingstone&quot;,
       decode(&quot;zmlyh gzxov rhlug vmzhg vkkrm thglm v&quot;)
   );
}

#[test]
//#[ignore]
fn test_decode_numbers() {
   assert_eq!(&quot;testing123testing&quot;, decode(&quot;gvhgr mt123 gvhgr mt&quot;));
}

#[test]
//#[ignore]
fn test_decode_all_the_letters() {
   assert_eq!(
       &quot;thequickbrownfoxjumpsoverthelazydog&quot;,
       decode(&quot;gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt&quot;)
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-36" id="4-答案-36"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn ascii(ch: char) -&gt; u8 {
   ch as u8
}

fn get_transpose(ch: char) -&gt; char {
   if ch.is_digit(10) {
       ch
   } else {
       (ascii('z') - ascii(ch) + ascii('a')) as char
   }
}

pub fn encode(plaintext: &amp;str) -&gt; String {
   plaintext
       .to_lowercase()
       .chars()
       .filter(|&amp;ch| ch.is_ascii())
       .filter(|&amp;ch| ch.is_alphanumeric())
       .map(|ch| get_transpose(ch))
       .collect::&lt;Vec&lt;char&gt;&gt;()
       .chunks(5)
       .map(|slice| slice.iter().cloned().collect::&lt;String&gt;())
       .collect::&lt;Vec&lt;String&gt;&gt;()
       .join(&quot; &quot;)
}

pub fn decode(ciphertext: &amp;str) -&gt; String {
   ciphertext
       .split::&lt;char&gt;(' ')
       .collect::&lt;String&gt;()
       .chars()
       .map(|ch| get_transpose(ch))
       .collect::&lt;String&gt;()
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-36" id="填充相关-36"><h2>填充/相关</h2></a>
<a class="header" href="#crypto-square" id="crypto-square"><h1>Crypto Square</h1></a>
<a class="header" href="#1-readme-37" id="1-readme-37"><h2>1. Readme</h2></a>
<a class="header" href="#加密广场" id="加密广场"><h1>加密广场</h1></a>
<p>实现，用于组成称为方形代码的加密信息的经典方法.</p>
<p>给定英文文本,输出该文本的加密编码版本。</p>
<p>首先,输入被规范化:</p>
<ul>
<li>从英文文本中删除空格和标点符号,并且消息是朝下的.</li>
</ul>
<p>然后,</p>
<ul>
<li>规范化字符被分成行。当使用插入的换行符打印时,这些行自自然然形成类似矩形的样子。</li>
</ul>
<p>例如,句子</p>
<pre><code class="language-text">&quot;If man was meant to stay on the ground, god would have given us roots.&quot;
</code></pre>
<p>规范化为:</p>
<pre><code class="language-text">&quot;ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots&quot;
</code></pre>
<p>明文应该组织成一个矩形。矩形的大小(<code>r x c</code>)应该根据消息的长度来决定<code>c &gt;= r</code>和<code>c - r &lt;= 1</code>,这里的<code>c</code>是列数和<code>r</code>是行数.</p>
<p>我们的标准化文本长度为 54 个字符，用<code>c = 8</code>和<code>r = 7</code>指示矩形:</p>
<pre><code class="language-text">&quot;ifmanwas&quot;
&quot;meanttos&quot;
&quot;tayonthe&quot;
&quot;groundgo&quot;
&quot;dwouldha&quot;
&quot;vegivenu&quot;
&quot;sroots  &quot;
</code></pre>
<p>通过向下(第一行第一个,拼接第二行第一个)，读取从左到右的列来获得编码消息.</p>
<p>上面的消息编码为:</p>
<pre><code class="language-text">&quot;imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau&quot;
</code></pre>
<p>根据输出的，矩形块编码文本的大小<code>(r X c)</code>，表明有<code>c</code>块<code>r</code>长度的编码字串，以空格分隔。对于那些<code>n</code>位字符，但少于规定的长度的，每个尾添一个空格。</p>
<pre><code class="language-text">&quot;imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn  sseoau &quot;
</code></pre>
<p>请注意,如果我们要堆叠这些,我们可以直观地，将密文解码回原始消息:
(第一行第一个，拼接第二行第一个...)</p>
<pre><code class="language-text">&quot;imtgdvs&quot;
&quot;fearwer&quot;
&quot;mayoogo&quot;
&quot;anouuio&quot;
&quot;ntnnlvt&quot;
&quot;wttddes&quot;
&quot;aohghn &quot;
&quot;sseoau &quot;
</code></pre>
<a class="header" href="#资源-27" id="资源-27"><h2>资源</h2></a>
<p>J Dalbey 的编程实践问题<a href="http://users.csc.calpoly.edu/%7Ejdalbey/103/Projects/ProgrammingPractice.html">http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html</a></p>
<a class="header" href="#2-开始你的表演-37" id="2-开始你的表演-37"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn encrypt(input: &amp;str) -&gt; String {
   unimplemented!(&quot;Encrypt {:?} using a square code&quot;, input)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-37" id="3-测试代码查看-37"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn test(input: &amp;str, output: &amp;str) {
   assert_eq!(&amp;encrypt(input), output);
}

#[test]
fn test_empty_input() {
   test(&quot;&quot;, &quot;&quot;)
}

#[test]
//#[ignore]
fn test_encrypt_also_decrypts_square() {
   // note that you only get the exact input back if:
   // 1. no punctuation
   // 2. even spacing
   // 3. all lowercase
   // 4. square input
   let example = &quot;lime anda coco anut&quot;;
   assert_eq!(example, &amp;encrypt(&amp;encrypt(example)));
}

#[test]
//#[ignore]
fn test_example() {
   test(
       &quot;If man was meant to stay on the ground, god would have given us roots.&quot;,
       &quot;imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn  sseoau &quot;,
   )
}

#[test]
//#[ignore]
fn test_empty_last_line() {
   test(&quot;congratulate&quot;, &quot;crl oaa ntt gue&quot;)
}

#[test]
//#[ignore]
fn test_spaces_are_reorganized() {
   test(&quot;abet&quot;, &quot;ae bt&quot;);
   test(&quot;a bet&quot;, &quot;ae bt&quot;);
   test(&quot;     a  b     e      t             &quot;, &quot;ae bt&quot;);
}

#[test]
//#[ignore]
fn test_everything_becomes_lowercase() {
   test(&quot;caSe&quot;, &quot;cs ae&quot;);
   test(&quot;cAsE&quot;, &quot;cs ae&quot;);
   test(&quot;CASE&quot;, &quot;cs ae&quot;);
}

#[test]
//#[ignore]
fn test_long() {
   test(
       r#&quot;
We choose to go to the moon.

We choose to go to the moon in this decade and do the other things,
not because they are easy, but because they are hard, because that
goal will serve to organize and measure the best of our energies and
skills, because that challenge is one that we are willing to accept,
one we are unwilling to postpone, and one which we intend to win,
and the others, too.

-- John F. Kennedy, 12 September 1962
       &quot;#,
       &amp;(String::from(&quot;womdbudlmecsgwdwob enooetbsenaotioihe &quot;)
           + &quot;cwotcbeeaeunolnnnr henhaecrsrsealeaf1 ocieucavugetciwnk9 &quot;
           + &quot;ohnosauerithcnhde6 sotteusteehaegitn2 eohhtseotsatptchn  &quot;
           + &quot;tsiehetohatwtohee  oesrethrenceopwod  gtdtyhagbdhanoety  &quot;
           + &quot;ooehaetaesaresih1  tgcirygnsklewtne2  ooaneaoitilweptrs  &quot;
           + &quot;ttdgerazoleiaoese  hoesaeleflnlrnntp  etanshwaosgleedot  &quot;
           + &quot;mhnoyainubeiuatoe  oedtbrldreinnnojm &quot;),
   )
}

#}</code></pre></pre>
<a class="header" href="#4-答案-37" id="4-答案-37"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
extern crate itertools;
use itertools::Itertools;

/// Encrypt the input string using square cryptography
pub fn encrypt(input: &amp;str) -&gt; String {
   let prepared = prepare(input);
   if prepared.len() == 0 {
       return String::new();
   }

   let (cols, rows) = dimensions(prepared.len());

   let mut output = String::with_capacity(input.len());
   for chunk_iterator in SquareIndexer::new(rows, cols).chunks(cols).into_iter() {
       for ch_idx in chunk_iterator {
           if ch_idx &lt; prepared.len() {
               output.push(prepared[ch_idx]);
           }
       }
       output.push(' ');
   }

   // we know there's one extra space at the end
   output.pop();

   output
}

/// Construct a vector of characters from the given input.
///
/// Constrain it to the allowed chars: lowercase ascii letters.
/// We construct a vector here because the length of the input
/// matters when constructing the output, so we need to know
/// how many input chars there are. We could treat it as a stream
/// and just stream twice, but collecting it into a vector works
/// equally well and might be a bit faster.
fn prepare(input: &amp;str) -&gt; Vec&lt;char&gt; {
   let mut output = Vec::with_capacity(input.len());

   output.extend(
       input
           .chars()
           .filter(|&amp;c| c.is_ascii() &amp;&amp; !c.is_whitespace() &amp;&amp; !c.is_ascii_punctuation())
           .map(|c| c.to_ascii_lowercase()),
   );

   // add space padding to the end such that the actual string returned
   // forms a perfect rectangle
   let (r, c) = dimensions(output.len());
   let padding_qty = (r * c) - output.len();
   for _ in 0..padding_qty {
       output.push(' ');
   }

   output.shrink_to_fit();

   output
}

/// Get the dimensions of the appropriate bounding rectangle for this encryption
///
/// To find `(rows, cols)` such that `cols &gt;= rows &amp;&amp; cols - rows &lt;= 1`, we find
/// the least square greater than or equal to the message length. Its square root
/// is the cols. If the message length is a perfect square, `rows` is the same.
/// Otherwise, it is one less.
fn dimensions(length: usize) -&gt; (usize, usize) {
   let cols = (length as f64).sqrt().ceil() as usize;
   let rows = if cols * cols == length {
       cols
   } else {
       cols - 1
   };
   (rows, cols)
}

/// Iterator over the indices of the appropriate chars of the output.
///
/// For a (2, 3) (r, c) grid, yields (0, 3, 1, 4, 2, 5).
/// Does no bounds checking or space insertion: that's handled elsewhere.
#[derive(Debug)]
struct SquareIndexer {
   rows: usize,
   cols: usize,
   cur_row: usize,
   cur_col: usize,
   max_value: usize,
}

impl SquareIndexer {
   fn new(rows: usize, cols: usize) -&gt; SquareIndexer {
       SquareIndexer {
           rows: rows,
           cols: cols,
           cur_row: 0,
           cur_col: 0,
           max_value: rows * cols,
       }
   }
}

impl Iterator for SquareIndexer {
   type Item = usize;
   fn next(&amp;mut self) -&gt; Option&lt;usize&gt; {
       let value = self.cur_row + (self.cur_col * self.rows);
       let output = if value &lt; self.max_value &amp;&amp; self.cur_row &lt; self.rows {
           Some(value)
       } else {
           None
       };

       // now increment internal state to next value
       self.cur_col += 1;
       if self.cur_col &gt;= self.cols {
           self.cur_col = 0;
           self.cur_row += 1;
       }

       output
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-37" id="填充相关-37"><h2>填充/相关</h2></a>
<a class="header" href="#rotational-cipher" id="rotational-cipher"><h1>Rotational Cipher</h1></a>
<a class="header" href="#1-readme-38" id="1-readme-38"><h2>1. Readme</h2></a>
<a class="header" href="#旋转密码" id="旋转密码"><h1>旋转密码</h1></a>
<p>创建旋转密码的实现,有时也称为 Caesar 密码.</p>
<p>Caesar 密码是一个简单的移位密码，它依赖于使用<code>0</code>到<code>26</code>整数(key)，在字母表中转置所有字母。由于模运算，使用<code>0</code>要么<code>26</code>，总是会产生相同的输出。将字母移动为与 key 值一样多的值。</p>
<p>旋转密码的一般表示法是<code>ROT + &lt;key&gt;</code>。最常用的旋转密码是<code>ROT13</code>.</p>
<p>一个拉丁字母表的<code>ROT13</code>加密如下:</p>
<pre><code class="language-text">原文:  abcdefghijklmnopqrstuvwxyz
密文:  nopqrstuvwxyzabcdefghijklm
</code></pre>
<p>它比 Atbash 密码更强大,因为它有 27 个可能性 key，和 25 个可用的密文.</p>
<p>密文会与输入相同的格式写出,包括空格和标点符号.</p>
<a class="header" href="#例子-5" id="例子-5"><h2>例子</h2></a>
<ul>
<li>ROT5 <code>omg</code>给<code>trl</code></li>
<li>ROT0 <code>c</code>给<code>c</code></li>
<li>ROT26 <code>Cool</code>给<code>Cool</code></li>
<li>ROT13 <code>The quick brown fox jumps over the lazy dog.</code>给<code>Gur dhvpx oebja sbk whzcf bire gur ynml qbt.</code></li>
<li>ROT13 <code>Gur dhvpx oebja sbk whzcf bire gur ynml qbt.</code>给<code>The quick brown fox jumps over the lazy dog.</code></li>
</ul>
<a class="header" href="#资源-28" id="资源-28"><h2>资源</h2></a>
<p>维基百科<a href="https://en.wikipedia.org/wiki/Caesar_cipher">https://en.wikipedia.org/wiki/Caesar_cipher</a></p>
<a class="header" href="#2-开始你的表演-38" id="2-开始你的表演-38"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn rotate(input: &amp;str, key: i8) -&gt; String {
   unimplemented!(
       &quot;How would input text '{}' transform when every letter is shifted using key '{}'?&quot;,
       input,
       key
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-38" id="3-测试代码查看-38"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn rotate_a_1() {
   assert_eq!(&quot;b&quot;, rotate(&quot;a&quot;, 1));
}

#[test]
//#[ignore]
fn rotate_a_26() {
   assert_eq!(&quot;a&quot;, rotate(&quot;a&quot;, 26));
}

#[test]
//#[ignore]
fn rotate_a_0() {
   assert_eq!(&quot;a&quot;, rotate(&quot;a&quot;, 0));
}

#[test]
//#[ignore]
fn rotate_m_13() {
   assert_eq!(&quot;z&quot;, rotate(&quot;m&quot;, 13));
}

#[test]
//#[ignore]
fn rotate_n_13_with_wrap() {
   assert_eq!(&quot;a&quot;, rotate(&quot;n&quot;, 13));
}

#[test]
//#[ignore]
fn rotate_caps() {
   assert_eq!(&quot;TRL&quot;, rotate(&quot;OMG&quot;, 5));
}

#[test]
//#[ignore]
fn rotate_spaces() {
   assert_eq!(&quot;T R L&quot;, rotate(&quot;O M G&quot;, 5));
}

#[test]
//#[ignore]
fn rotate_numbers() {
   assert_eq!(&quot;Xiwxmrk 1 2 3 xiwxmrk&quot;, rotate(&quot;Testing 1 2 3 testing&quot;, 4));
}

#[test]
//#[ignore]
fn rotate_punctuation() {
   assert_eq!(&quot;Gzo\'n zvo, Bmviyhv!&quot;, rotate(&quot;Let\'s eat, Grandma!&quot;, 21));
}

#[test]
//#[ignore]
fn rotate_all_the_letters() {
   assert_eq!(
       &quot;Gur dhvpx oebja sbk whzcf bire gur ynml qbt.&quot;,
       rotate(&quot;The quick brown fox jumps over the lazy dog.&quot;, 13)
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-38" id="4-答案-38"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn rotate(text: &amp;str, shift_key: u8) -&gt; String {
   text.chars()
       .map(|c| {
           let case = if c.is_uppercase() { 'A' } else { 'a' } as u8;
           if c.is_alphabetic() {
               (((c as u8 - case + shift_key) % 26) + case) as char
           } else {
               c
           }
       })
       .collect::&lt;String&gt;()
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-38" id="填充相关-38"><h2>填充/相关</h2></a>
<a class="header" href="#simple-cipher" id="simple-cipher"><h1>Simple Cipher</h1></a>
<a class="header" href="#1-readme-39" id="1-readme-39"><h2>1. Readme</h2></a>
<a class="header" href="#简单密码" id="简单密码"><h1>简单密码</h1></a>
<p>实现一个简单的移位密码,像 Caesar 和，一个更安全的替换密码.</p>
<a class="header" href="#步骤-1-2" id="步骤-1-2"><h2>步骤 1</h2></a>
<p>“如果他有什么秘密要说的话，他就是用密码写的，也就是说，通过改变字母表的字母顺序，一个字也说不出来。如果有人想破译这些，并理解它们的意思，他必须用字母表中的第四个字母，即 D，代替 A，以及其他的字母。
—Suetonius, Life of Julius Caesar</p>
<p>密码是非常直截了当的算法，使文本不可读，同时仍容易允许破译。他们容易受到许多形式的密码分析，但我们幸运的是，我们的小姐妹通常不是密码学家。</p>
<p>用 Caesar密码，加密来自 Julius Caesar 的消息。现在 Caesar 知道加密方式不是很好，但他还是有个好处: 几乎没有人能读对。所以对于一对夫妇的信件已经足够了，让人们无法识别他们所知道的几个字。</p>
<p>你的任务是创建一个简单的移位密码，就像 Caesar 密码一样。这个图像是 Caesar 密码的一个很好的例子:</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/4a/Caesar_cipher_left_shift_of_3.svg/320px-Caesar_cipher_left_shift_of_3.svg.png" alt="Caesar Cipher" /></p>
<p>例如:</p>
<p>将”iamapandabear”作为输入到 <code>encode</code> 函数返回密码”ldpdsdqgdehdu”。(虽不足以让我们的信息在运输过程中，确保高保密性).</p>
<p>当将”ldpdsdqgdehdu”放入<code>decode</code>函数时，它将返回原始的”iamapandabear”，让您的朋友阅读您的原始消息.</p>
<a class="header" href="#步骤-2" id="步骤-2"><h2>步骤 2</h2></a>
<p>移位密码是没有乐趣，直到你的妹妹算了出来后！尝试修改代码,允许我们指定一个密钥(key)，并用作移位距离。这称为代换密码.</p>
<p>下面是一个例子:</p>
<p>给定密钥”aaaaaaaaaaaaaaaaaaa”，对字符串”iamapandabar”进行编码将返回原来的”iamapandable”.</p>
<p>给定密钥”ddddddddddddd”，编码我们的字符串”iamapandabore”会返回疑惑的”ldpdsdqgdhdu”.</p>
<p>在上面的示例中,我们为键值设置了 <code>a=0</code>。因此,当明文添加到密钥时,我们最终得到相同的消息。所以”aaaa”不是一个理想的密钥。但是,如果我们把密钥设置为<code>dddd</code>,我们将得到与 caesar 密码相同的东西.</p>
<a class="header" href="#步骤-3" id="步骤-3"><h2>步骤 3</h2></a>
<p>任何密码中最薄弱的环节都是人。让我们通过提供随机性，并确保密钥仅包含小写字母，来使替换密码更具容错性.</p>
<p>如果有人根本不提交密钥,则生成一个长度至少为 100 个字符的真正随机密钥.</p>
<p>如果提交的密钥不只由小写字母组成,那解决方案应该以适当提醒的方式处理错误.</p>
<a class="header" href="#扩展-4" id="扩展-4"><h2>扩展</h2></a>
<p>移位密码通过使文本略微疑惑，达到目的，但易受频率分析的影响。替换密码有助于这一点,但当密钥较短，或空格被保留时,仍然非常脆弱。稍后,你会看到一个解决这个问题的练习”crypto-square”.</p>
<p>如果你想在这一领域走得更远，问题引导你，走进如何以安全的方式交换密钥。看一看<a href="http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange">维基百科上的 Diffie Hellman</a>对于该方案的最早实现之一.</p>
<a class="header" href="#资源-29" id="资源-29"><h2>资源</h2></a>
<p>维基百科的替代密码<a href="http://en.wikipedia.org/wiki/Substitution_cipher">http://en.wikipedia.org/wiki/Substitution_cipher</a></p>
<a class="header" href="#2-开始你的表演-39" id="2-开始你的表演-39"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn encode(key: &amp;str, s: &amp;str) -&gt; Option&lt;String&gt; {
   unimplemented!(&quot;Use {} to encode {} using shift cipher&quot;, key, s)
}

pub fn decode(key: &amp;str, s: &amp;str) -&gt; Option&lt;String&gt; {
   unimplemented!(&quot;Use {} to decode {} using shift cipher&quot;, key, s)
}

pub fn encode_random(s: &amp;str) -&gt; (String, String) {
   unimplemented!(
       &quot;Generate random key with only a-z chars and encode {}. Return tuple (key, encoded s)&quot;,
       s
   )
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-39" id="3-测试代码查看-39"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashSet;

const PLAIN_TEXT: &amp;str = &quot;thisismysecret&quot;;
const KEY: &amp;str = &quot;abcdefghij&quot;;

#[test]
fn cipher_can_encode_with_given_key() {
   assert_eq!(encode(KEY, &quot;aaaaaaaaaa&quot;), Some(KEY.to_string()));
}

#[test]
//#[ignore]
fn cipher_can_decode_with_given_key() {
   assert_eq!(decode(KEY, &quot;abcdefghij&quot;), Some(&quot;aaaaaaaaaa&quot;.to_string()));
}

#[test]
//#[ignore]
fn cipher_is_reversible_given_key() {
   assert_eq!(
       decode(KEY, &amp;encode(KEY, PLAIN_TEXT).unwrap()),
       Some(PLAIN_TEXT.to_string())
   );
}

#[test]
//#[ignore]
fn cipher_can_double_shift_encode() {
   let plain_text = &quot;iamapandabear&quot;;
   assert_eq!(
       encode(plain_text, plain_text),
       Some(&quot;qayaeaagaciai&quot;.to_string())
   );
}

#[test]
//#[ignore]
fn cipher_can_wrap_encode() {
   assert_eq!(encode(KEY, &quot;zzzzzzzzzz&quot;), Some(&quot;zabcdefghi&quot;.to_string()));
}

#[test]
//#[ignore]
fn cipher_can_encode_a_message_that_is_shorter_than_the_key() {
   assert_eq!(encode(KEY, &quot;aaaaa&quot;), Some(&quot;abcde&quot;.to_string()));
}

#[test]
//#[ignore]
fn cipher_can_decode_a_message_that_is_shorter_than_the_key() {
   assert_eq!(decode(KEY, &quot;abcde&quot;), Some(&quot;aaaaa&quot;.to_string()));
}

#[test]
//#[ignore]
fn encode_returns_none_with_an_all_caps_key() {
   let key = &quot;ABCDEF&quot;;
   assert_eq!(encode(key, PLAIN_TEXT), None);
}

#[test]
//#[ignore]
fn encode_returns_none_with_an_any_caps_key() {
   let key = &quot;abcdEFg&quot;;
   assert_eq!(encode(key, PLAIN_TEXT), None);
}

#[test]
//#[ignore]
fn encode_returns_none_with_numeric_key() {
   let key = &quot;12345&quot;;
   assert_eq!(encode(key, PLAIN_TEXT), None);
}

#[test]
//#[ignore]
fn encode_returns_none_with_any_numeric_key() {
   let key = &quot;abcd345ef&quot;;
   assert_eq!(encode(key, PLAIN_TEXT), None);
}

#[test]
//#[ignore]
fn encode_returns_none_with_empty_key() {
   let key = &quot;&quot;;
   assert_eq!(encode(key, PLAIN_TEXT), None);
}

#[test]
//#[ignore]
fn decode_returns_none_with_an_all_caps_key() {
   let key = &quot;ABCDEF&quot;;
   assert_eq!(decode(key, PLAIN_TEXT), None);
}

#[test]
//#[ignore]
fn decode_returns_none_with_an_any_caps_key() {
   let key = &quot;abcdEFg&quot;;
   assert_eq!(decode(key, PLAIN_TEXT), None);
}

#[test]
//#[ignore]
fn decode_returns_none_with_numeric_key() {
   let key = &quot;12345&quot;;
   assert_eq!(decode(key, PLAIN_TEXT), None);
}

#[test]
//#[ignore]
fn decode_returns_none_with_any_numeric_key() {
   let key = &quot;abcd345ef&quot;;
   assert_eq!(decode(key, PLAIN_TEXT), None);
}

#[test]
//#[ignore]
fn decode_returns_none_with_empty_key() {
   let key = &quot;&quot;;
   assert_eq!(decode(key, PLAIN_TEXT), None);
}

#[test]
//#[ignore]
fn encode_random_uses_key_made_of_letters() {
   let (k, _) = encode_random(PLAIN_TEXT);
   assert!(k.chars().all(|c| c.is_ascii_lowercase()));
}

#[test]
//#[ignore]
fn encode_random_uses_key_of_100_characters_or_more() {
   let (k, _) = encode_random(PLAIN_TEXT);
   assert!(k.len() &gt;= 100);
}

#[test]
//#[ignore]
fn encode_random_uses_randomly_generated_key() {
   let mut keys = HashSet::new();
   let trials = 100;
   for _ in 0..trials {
       keys.insert(encode_random(PLAIN_TEXT).0);
   }
   assert_eq!(keys.len(), trials);
}

#[test]
//#[ignore]
fn encode_random_can_encode() {
   let (k, encoded) = encode_random(&quot;aaaaaaaaaa&quot;);
   assert_eq!(encoded, k.split_at(10).0);
}

#[test]
//#[ignore]
fn encode_random_can_decode() {
   let (k, _) = encode_random(&quot;aaaaaaaaaa&quot;);
   assert_eq!(decode(&amp;k, k.split_at(10).0), Some(&quot;aaaaaaaaaa&quot;.to_string()));
}

#[test]
//#[ignore]
fn encode_random_is_reversible() {
   let (k, encoded) = encode_random(PLAIN_TEXT);
   assert_eq!(decode(&amp;k, &amp;encoded), Some(PLAIN_TEXT.to_string()));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-39" id="4-答案-39"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
extern crate rand;
use rand::Rng;

pub fn encode_random(s: &amp;str) -&gt; (String, String) {
   let mut r = rand::thread_rng();
   let mut key = String::new();
   for _ in 0..100 {
       key.push(char::from('a' as u8 + r.gen_range(0, 26)));
   }
   let encoded = encode(&amp;key, s);
   (key, encoded.unwrap())
}

pub fn encode(key: &amp;str, s: &amp;str) -&gt; Option&lt;String&gt; {
   shift(key, s, 1)
}

pub fn decode(key: &amp;str, s: &amp;str) -&gt; Option&lt;String&gt; {
   shift(key, s, -1)
}

fn shift(key: &amp;str, s: &amp;str, dir: i8) -&gt; Option&lt;String&gt; {
   if key.is_empty() {
       return None;
   }
   let mut o = String::new();
   let mut i = 0;
   let mut key_arr = Vec::new();
   for c in key.chars() {
       if !c.is_ascii_lowercase() {
           return None;
       }
       key_arr.push(c);
   }
   for c in s.chars() {
       let shift = key_arr[i % key_arr.len()] as i8 - 'a' as i8;
       let n = ((c as i8 - 'a' as i8 + dir * shift) % 26 + 26) % 26;
       o.push(char::from('a' as u8 + n as u8));
       i += 1;
   }
   Some(o)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-39" id="填充相关-39"><h2>填充/相关</h2></a>
<a class="header" href="#rail-fence-cipher" id="rail-fence-cipher"><h1>Rail Fence Cipher</h1></a>
<a class="header" href="#1-readme-40" id="1-readme-40"><h2>1. Readme</h2></a>
<a class="header" href="#篱笆密码法栅栏密码" id="篱笆密码法栅栏密码"><h1>篱笆密码法(栅栏密码)</h1></a>
<p>实现篱笆密码法的编/解码.</p>
<p>篱笆密码法是一种置换式密码,它从编码的方式得到它的名字。它早被古希腊人所使用。</p>
<p>在 栅栏 密码中,信息向下写在虚构的篱笆的连续”rail”上，然后当我们到达底部时，又向上移动(像锯齿形)。最后,消息以行读取.</p>
<p>例如,使用三个”Rails(栅栏)”，和加密”WE ARE DISCOVERED FLEE AT ONCE”信息，密文写道:</p>
<pre><code class="language-text">W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . A . . . I . . . V . . . D . . . E . . . N . .
</code></pre>
<p>然后读出:</p>
<pre><code class="language-text">WECRLTEERDSOEEFEAOCAIVDEN
</code></pre>
<p>要解密一条消息,你要采用锯齿形读法，而密文则是一行一行看。</p>
<pre><code class="language-text">? . . . ? . . . ? . . . ? . . . ? . . . ? . . . ?
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
</code></pre>
<p>第一行有七个点,可以用”WECRRLTE”填充.</p>
<pre><code class="language-text">W . . . E . . . C . . . R . . . L . . . T . . . E
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
</code></pre>
<p>现在第二行为”ERDSOEEFEAOC”.</p>
<pre><code class="language-text">W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .
</code></pre>
<p>最后一排”AIVDEN”.</p>
<pre><code class="language-text">W(1) . . . E . . . C . . . R . . . L . . . T . . . E
. E(2) . R . D . S . O . E . E . F . E . A . O . C .
. . A(3) . . . I . . . V . . . D . . . E . . . N . .
</code></pre>
<blockquote>
<p><code>1,2,3</code>只是为了方便理解，不存在任何地方</p>
</blockquote>
<p>如果你现在锯齿形阅读,你可以阅读原始消息.</p>
<a class="header" href="#资源-30" id="资源-30"><h2>资源</h2></a>
<p>维基百科<a href="https://en.wikipedia.org/wiki/Transposition_cipher#Rail_Fence_cipher">https://en.wikipedia.org/wiki/Transposition_cipher#Rail_Fence_cipher</a></p>
<p>百度百科
<a href="https://baike.baidu.com/item/%E6%A0%85%E6%A0%8F%E5%AF%86%E7%A0%81">https://baike.baidu.com/item/%E6%A0%85%E6%A0%8F%E5%AF%86%E7%A0%81</a></p>
<a class="header" href="#2-开始你的表演-40" id="2-开始你的表演-40"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub struct RailFence;

impl RailFence {
   pub fn new(rails: u32) -&gt; RailFence {
       unimplemented!(&quot;Construct a new fence with {} rails&quot;, rails)
   }

   pub fn encode(&amp;self, text: &amp;str) -&gt; String {
       unimplemented!(&quot;Encode this text: {}&quot;, text)
   }

   pub fn decode(&amp;self, cipher: &amp;str) -&gt; String {
       unimplemented!(&quot;Decode this ciphertext: {}&quot;, cipher)
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-40" id="3-测试代码查看-40"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
/// Tests for rail-fence-cipher
///
/// Generated by [script][script] using [canonical data][canonical-data]
///
/// [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
/// [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/rail-fence-cipher/canonical_data.json
///
/// The tests do not expect any normalization or cleaning.
/// That trade is tested in enough other exercises.

/// Process a single test case for the property `encode`
///
/// All cases for the `encode` property are implemented
/// in terms of this function.
fn process_encode_case(input: &amp;str, rails: u32, expected: &amp;str) {
   let rail_fence = RailFence::new(rails);
   assert_eq!(rail_fence.encode(input), expected);
}

/// Process a single test case for the property `decode`
///
/// All cases for the `decode` property are implemented
/// in terms of this function.
fn process_decode_case(input: &amp;str, rails: u32, expected: &amp;str) {
   let rail_fence = RailFence::new(rails);
   assert_eq!(rail_fence.decode(input), expected);
}

// encode

#[test]
/// encode with two rails
fn test_encode_with_two_rails() {
   process_encode_case(&quot;XOXOXOXOXOXOXOXOXO&quot;, 2, &quot;XXXXXXXXXOOOOOOOOO&quot;);
}

#[test]
//#[ignore]
/// encode with three rails
fn test_encode_with_three_rails() {
   process_encode_case(&quot;WEAREDISCOVEREDFLEEATONCE&quot;, 3, &quot;WECRLTEERDSOEEFEAOCAIVDEN&quot;);
}

#[test]
//#[ignore]
/// encode with ending in the middle
fn test_encode_with_ending_in_the_middle() {
   process_encode_case(&quot;EXERCISES&quot;, 4, &quot;ESXIEECSR&quot;);
}

// decode

#[test]
//#[ignore]
/// decode with three rails
fn test_decode_with_three_rails() {
   process_decode_case(&quot;TEITELHDVLSNHDTISEIIEA&quot;, 3, &quot;THEDEVILISINTHEDETAILS&quot;);
}

#[test]
//#[ignore]
/// decode with five rails
fn test_decode_with_five_rails() {
   process_decode_case(&quot;EIEXMSMESAORIWSCE&quot;, 5, &quot;EXERCISMISAWESOME&quot;);
}

#[test]
//#[ignore]
/// decode with six rails
fn test_decode_with_six_rails() {
   process_decode_case(
       &quot;133714114238148966225439541018335470986172518171757571896261&quot;,
       6,
       &quot;112358132134558914423337761098715972584418167651094617711286&quot;,
   );
}

#[test]
//#[ignore]
/// encode wide characters
///
/// normally unicode is not part of exercism exercises, but in an exercise
/// specifically oriented around shuffling characters, it seems worth ensuring
/// that wide characters are handled properly
///
/// this text is possibly one of the most famous haiku of all time, by
/// Matsuo Bashō (松尾芭蕉)
fn test_encode_wide_characters() {
   process_encode_case(
       &quot;古池 蛙飛び込む 水の音&quot;,
       3,
       &quot;古飛 池蛙びむ水音 込の&quot;,
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-40" id="4-答案-40"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub struct RailFence(u32);

fn uncons(s: &amp;str) -&gt; (&amp;str, &amp;str) {
   s.split_at(s.chars().next().map_or(0, |c| c.len_utf8()))
}

impl RailFence {
   pub fn new(rails: u32) -&gt; RailFence {
       RailFence(rails)
   }

   fn next(&amp;self, down: &amp;mut bool, rail: &amp;mut usize) {
       if *down {
           if *rail + 1 &lt; self.0 as usize {
               *rail += 1;
           } else {
               *down = false;
               *rail -= 1;
           }
       } else {
           if *rail &gt; 0 {
               *rail -= 1;
           } else {
               *down = true;
               *rail += 1;
           }
       }
   }

   pub fn encode(&amp;self, text: &amp;str) -&gt; String {
       let mut rails =
           vec![String::with_capacity(1 + (text.len() / self.0 as usize)); self.0 as usize];
       let mut down = true;
       let mut rail = 0;

       for ch in text.chars() {
           rails[rail].push(ch);
           self.next(&amp;mut down, &amp;mut rail);
       }

       rails.join(&quot;&quot;)
   }

   pub fn decode(&amp;self, cipher: &amp;str) -&gt; String {
       let mut rail_caps = vec![0; self.0 as usize];
       let mut down = true;
       let mut rail = 0;

       for _ in cipher.chars() {
           rail_caps[rail] += 1;
           self.next(&amp;mut down, &amp;mut rail);
       }

       // this vector owns the text of each rail
       let mut rails_own = Vec::with_capacity(self.0 as usize);
       let mut skip = 0;

       for &amp;cap in rail_caps.iter() {
           rails_own.push(
               cipher
                   .chars()
                   .skip(skip)
                   .enumerate()
                   .take_while(|&amp;(i, _)| i &lt; cap)
                   .map(|(_, c)| c)
                   .collect::&lt;String&gt;(),
           );
           skip += cap;
       }

       // this vector holds string slices viewing into rails_own
       let mut rails: Vec&lt;&amp;str&gt; = rails_own.iter().map(|r| r.as_ref()).collect();

       let mut out = String::with_capacity(cipher.len());
       down = true;
       rail = 0;

       while rails.iter().any(|r: &amp;&amp;str| r.len() &gt; 0) {
           let (head, t_rail) = uncons(rails[rail]);
           rails[rail] = t_rail;
           self.next(&amp;mut down, &amp;mut rail);
           out.push_str(head);
       }

       out
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-40" id="填充相关-40"><h2>填充/相关</h2></a>
<a class="header" href="#etl" id="etl"><h1>ETL</h1></a>
<a class="header" href="#1-readme-41" id="1-readme-41"><h2>1. Readme</h2></a>
<a class="header" href="#etl-1" id="etl-1"><h1>ETL</h1></a>
<p>ETL，是英文 <code>Extract-Transform-Load</code> 的缩写，用来描述将数据从来源端经过萃取、转置、加载至目的端的过程</p>
<a class="header" href="#etl-2" id="etl-2"><h3>ETL</h3></a>
<p>提取转换负载(ETL)是一种很有意思的说法,”我们在这个系统中有一些遗留的遗留数据,现在我们需要在这个闪亮的新系统中使用,所以我们将迁移它.”</p>
<p>(通常情况下,接下来是，”我们只需要运行一次就好啦。”之后，通常会有很多怒拍额头,并抱怨自身有多么愚蠢。</p>
<a class="header" href="#目标" id="目标"><h3>目标</h3></a>
<p>我们将从遗留系统中，提取一些拼字游戏分数.</p>
<p>旧的系统存储每一个字母的列表:</p>
<ul>
<li>1 分:”A”,”E”,”I”,”O”,”U”,”L”,”N”,”R”,”S”,”T”,</li>
<li>2 分:”D”,”G”,</li>
<li>3 分:”B”、”C”、”M”、”P”,</li>
<li>4 分:”F”、”H”、”V”、”W”、”Y”,</li>
<li>5 分:”K”,</li>
<li>8 分:”J”,”X”,</li>
<li>10 分:”Q”,”Z”,</li>
</ul>
<p>闪亮的新拼写系统存储每个字母的分数，这使得计算一个单词的分数更快、更容易。它也把字母存为小写字母，而不考虑输入字母的情况:</p>
<ul>
<li>“a” 值 1 分.</li>
<li>“b” 值 3 分.</li>
<li>“c” 值 3 分.</li>
<li>“d” 值 2 分.</li>
<li>等.</li>
</ul>
<p>你的任务,你应该选择接受它, 应将遗留数据格式，转换成闪亮的新格式。</p>
<a class="header" href="#笔记-1" id="笔记-1"><h3>笔记</h3></a>
<p>关于得分的最后一点是,Scrabble 这款游戏在世界各地，多个国家，每种语言都有自己独特的得分表。例如,在毛利(Māori)语版本的游戏中,”E”得分为 2 分,而在夏威夷语版本中为 4 分。</p>
<a class="header" href="#资源-31" id="资源-31"><h2>资源</h2></a>
<p>JunpStab 实验室团队<a href="http://jumpstartlab.com">http://jumpstartlab.com</a></p>
<a class="header" href="#2-开始你的表演-41" id="2-开始你的表演-41"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::collections::BTreeMap;

pub fn transform(h: &amp;BTreeMap&lt;i32, Vec&lt;char&gt;&gt;) -&gt; BTreeMap&lt;char, i32&gt; {
   unimplemented!(&quot;How will you transform the tree {:?}?&quot;, h)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-41" id="3-测试代码查看-41"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_transform_one_value() {
   let input = input_from(&amp;[(1, vec!['A'])]);

   let expected = expected_from(&amp;[('a', 1)]);

   assert_eq!(expected, transform(&amp;input));
}

#[test]
//#[ignore]
fn test_transform_more_values() {
   let input = input_from(&amp;[(1, vec!['A', 'E', 'I', 'O', 'U'])]);

   let expected = expected_from(&amp;[('a', 1), ('e', 1), ('i', 1), ('o', 1), ('u', 1)]);

   assert_eq!(expected, transform(&amp;input));
}

#[test]
//#[ignore]
fn test_more_keys() {
   let input = input_from(&amp;[(1, vec!['A', 'E']), (2, vec!['D', 'G'])]);

   let expected = expected_from(&amp;[('a', 1), ('e', 1), ('d', 2), ('g', 2)]);

   assert_eq!(expected, transform(&amp;input));
}

#[test]
//#[ignore]
fn test_full_dataset() {
   let input = input_from(&amp;[
       (1, vec!['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T']),
       (2, vec!['D', 'G']),
       (3, vec!['B', 'C', 'M', 'P']),
       (4, vec!['F', 'H', 'V', 'W', 'Y']),
       (5, vec!['K']),
       (8, vec!['J', 'X']),
       (10, vec!['Q', 'Z']),
   ]);

   let expected = expected_from(&amp;[
       ('a', 1),
       ('b', 3),
       ('c', 3),
       ('d', 2),
       ('e', 1),
       ('f', 4),
       ('g', 2),
       ('h', 4),
       ('i', 1),
       ('j', 8),
       ('k', 5),
       ('l', 1),
       ('m', 3),
       ('n', 1),
       ('o', 1),
       ('p', 3),
       ('q', 10),
       ('r', 1),
       ('s', 1),
       ('t', 1),
       ('u', 1),
       ('v', 4),
       ('w', 4),
       ('x', 8),
       ('y', 4),
       ('z', 10),
   ]);

   assert_eq!(expected, transform(&amp;input));
}

fn input_from(v: &amp;[(i32, Vec&lt;char&gt;)]) -&gt; BTreeMap&lt;i32, Vec&lt;char&gt;&gt; {
   v.iter().cloned().collect()
}

fn expected_from(v: &amp;[(char, i32)]) -&gt; BTreeMap&lt;char, i32&gt; {
   v.iter().cloned().collect()
}

#}</code></pre></pre>
<a class="header" href="#4-答案-41" id="4-答案-41"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::BTreeMap;

pub fn transform(input: &amp;BTreeMap&lt;i32, Vec&lt;char&gt;&gt;) -&gt; BTreeMap&lt;char, i32&gt; {
   input
       .iter()
       .flat_map(|(&amp;n, vec)| vec.iter().map(move |c| (c.to_ascii_lowercase(), n)))
       .collect()
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-41" id="填充相关-41"><h2>填充/相关</h2></a>
<a class="header" href="#accumulate" id="accumulate"><h1>Accumulate</h1></a>
<a class="header" href="#1-readme-42" id="1-readme-42"><h2>1. Readme</h2></a>
<a class="header" href="#accumulate-1" id="accumulate-1"><h1>Accumulate</h1></a>
<p>实现<code>accumulate</code>操作, 给出一个集合，和一个操作行为，该行为会影响到集合中的每个值，并返回一个新的，包含影响结果值的集合</p>
<p>如:给出数字的集合:</p>
<ul>
<li><code>1,2,3,4,5</code></li>
</ul>
<p>和一个平方操作:</p>
<ul>
<li>平方它(<code>x =&gt; x * x</code>)</li>
</ul>
<p>您的代码应该能够生成原集合的平方集合:</p>
<ul>
<li><code>1,4,9,16,25</code></li>
</ul>
<p>查看测试套件，以查看预期的函数命名.</p>
<a class="header" href="#限制" id="限制"><h2>限制</h2></a>
<p>请不要使用，标准库提供的 <code>collect/map/fmap/whatchamacallit</code> 函数! 使用其他基本工具自己解决这个问题.</p>
<a class="header" href="#提示" id="提示"><h2>提示</h2></a>
<p>看看 Fn traits 可能会有所帮助:<a href="https://doc.rust-lang.org/std/ops/trait.Fn.html">Fn</a>,<a href="https://doc.rust-lang.org/std/ops/trait.Fn.html">FnMut</a>和<a href="https://doc.rust-lang.org/std/ops/trait.Fn.html">FnOnce</a>.</p>
<p>有关将闭包传递给函数的帮助可以在<a href="https://rustwiki.org/zh-CN/rust-by-example/fn/closures/input_parameters.html">“闭包作为输入参数” 章节</a>里面，更多可看<a href="https://rustwiki.org/zh-CN/rust-by-example">Rust by Example</a>.</p>
<blockquote>
<p>改为中文网址</p>
</blockquote>
<p>如果您的函数命名不适合它们，即使它们没有运行,此练习的测试也会导致编译时错误。您可能希望对某些测试进行注释，并逐个击破。</p>
<a class="header" href="#资源-32" id="资源-32"><h2>资源</h2></a>
<p>与 James Edward Gray II 的对话<a href="https://twitter.com/jeg2">https://twitter.com/jeg2</a></p>
<a class="header" href="#2-开始你的表演-42" id="2-开始你的表演-42"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">/// What should the type of _function be?
pub fn map(input: Vec&lt;i32&gt;, _function: ???) -&gt; Vec&lt;i32&gt; {
   unimplemented!(&quot;Transform input vector {:?} using passed function&quot;, input);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-42" id="3-测试代码查看-42"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn square(x: i32) -&gt; i32 {
   x * x
}

#[test]
fn func_single() {
   let input = vec![2];
   let expected = vec![4];
   assert_eq!(map(input, square), expected);
}

#[test]
//#[ignore]
fn func_multi() {
   let input = vec![2, 3, 4, 5];
   let expected = vec![4, 9, 16, 25];
   assert_eq!(map(input, square), expected);
}

#[test]
//#[ignore]
fn closure() {
   let input = vec![2, 3, 4, 5];
   let expected = vec![4, 9, 16, 25];
   assert_eq!(map(input, |x| x * x), expected);
}

#[test]
//#[ignore]
fn closure_floats() {
   let input = vec![2.0, 3.0, 4.0, 5.0];
   let expected = vec![4.0, 9.0, 16.0, 25.0];
   assert_eq!(map(input, |x| x * x), expected);
}

#[test]
//#[ignore]
fn strings() {
   let input = vec![&quot;1&quot;.to_string(), &quot;2&quot;.into(), &quot;3&quot;.into()];
   let expected = vec![&quot;11&quot;.to_string(), &quot;22&quot;.into(), &quot;33&quot;.into()];
   assert_eq!(map(input, |s| s.repeat(2)), expected);
}

#[test]
//#[ignore]
fn change_in_type() {
   let input: Vec&lt;&amp;str&gt; = vec![&quot;1&quot;, &quot;2&quot;, &quot;3&quot;];
   let expected: Vec&lt;String&gt; = vec![&quot;1&quot;.into(), &quot;2&quot;.into(), &quot;3&quot;.into()];
   assert_eq!(map(input, |s| s.to_string()), expected);
}

#[test]
//#[ignore]
fn mutating_closure() {
   let mut counter = 0;
   let input = vec![-2, 3, 4, -5];
   let expected = vec![2, 3, 4, 5];
   let result = map(input, |x: i64| {
       counter += 1;
       x.abs()
   });
   assert_eq!(result, expected);
   assert_eq!(counter, 4);
}

#[test]
//#[ignore]
fn minimal_bounds_on_input_and_output() {
   // must be able to accept arbitrary input and output types
   struct Foo;
   struct Bar;
   map(vec![Foo], |_| Bar);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-42" id="4-答案-42"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn map&lt;F, T, U&gt;(values: Vec&lt;T&gt;, mut f: F) -&gt; Vec&lt;U&gt;
where
   F: FnMut(T) -&gt; U,
{
   let mut v = Vec::with_capacity(values.len());
   for val in values {
       v.push(f(val));
   }
   v
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-42" id="填充相关-42"><h2>填充/相关</h2></a>
<a class="header" href="#acronym" id="acronym"><h1>Acronym</h1></a>
<a class="header" href="#1-readme-43" id="1-readme-43"><h2>1. Readme</h2></a>
<a class="header" href="#缩写" id="缩写"><h1>缩写</h1></a>
<p>将短语转换为，其首字母缩写词。</p>
<p>技术人员都喜欢他们的 TLA(三字母缩略语(Three Letter Acronyms)显得高大上)!</p>
<p>通过编写将诸如 Portable Network Graphics 之类的长名称，转换为其首字母缩略词(PNG)的程序,帮助生成一些术语。</p>
<a class="header" href="#资源-33" id="资源-33"><h2>资源</h2></a>
<p>Julien Vanier<a href="https://github.com/monkbroc">https://github.com/monkbroc</a></p>
<a class="header" href="#2-开始你的表演-43" id="2-开始你的表演-43"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn abbreviate(phrase: &amp;str) -&gt; String {
   unimplemented!(&quot;Given the phrase '{}', return its acronym&quot;, phrase);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-43" id="3-测试代码查看-43"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn empty() {
   assert_eq!(abbreviate(&quot;&quot;), &quot;&quot;);
}

#[test]
//#[ignore]
fn basic() {
   assert_eq!(abbreviate(&quot;Portable Network Graphics&quot;), &quot;PNG&quot;);
}

#[test]
//#[ignore]
fn lowercase_words() {
   assert_eq!(abbreviate(&quot;Ruby on Rails&quot;), &quot;ROR&quot;);
}

#[test]
//#[ignore]
fn camelcase() {
   assert_eq!(abbreviate(&quot;HyperText Markup Language&quot;), &quot;HTML&quot;);
}

#[test]
//#[ignore]
fn punctuation() {
   assert_eq!(abbreviate(&quot;First In, First Out&quot;), &quot;FIFO&quot;);
}

#[test]
//#[ignore]
fn all_caps_words() {
   assert_eq!(abbreviate(&quot;PHP: Hypertext Preprocessor&quot;), &quot;PHP&quot;);
}

#[test]
//#[ignore]
fn non_acronym_all_caps_word() {
   assert_eq!(abbreviate(&quot;GNU Image Manipulation Program&quot;), &quot;GIMP&quot;);
}

#[test]
//#[ignore]
fn hyphenated() {
   assert_eq!(
       abbreviate(&quot;Complementary metal-oxide semiconductor&quot;),
       &quot;CMOS&quot;
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-43" id="4-答案-43"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn abbreviate(phrase: &amp;str) -&gt; String {
   phrase
       .split(|c: char| c.is_whitespace() || !c.is_alphanumeric())
       .flat_map(|word| split_camel(word))
       .filter_map(|word| word.chars().next())
       .collect::&lt;String&gt;()
       .to_uppercase()
}

fn split_camel(phrase: &amp;str) -&gt; Vec&lt;String&gt; {
   let chars: Vec&lt;char&gt; = phrase.chars().collect();
   let mut words: Vec&lt;String&gt; = Vec::new();
   let mut word_start: usize = 0;
   for (i, c) in chars.iter().enumerate() {
       if i == chars.len() - 1 || c.is_lowercase() &amp;&amp; chars[i + 1].is_uppercase() {
           words.push(chars[word_start..i + 1].iter().cloned().collect());
           word_start = i + 1;
       }
   }
   words
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-43" id="填充相关-43"><h2>填充/相关</h2></a>
<a class="header" href="#sieve" id="sieve"><h1>Sieve</h1></a>
<a class="header" href="#1-readme-44" id="1-readme-44"><h2>1. Readme</h2></a>
<a class="header" href="#素数筛" id="素数筛"><h1>素数筛</h1></a>
<p>使用 Eratosthenes 的 Sieve 查找从 2 到给定数字的所有素数.</p>
<p>这是一种简单且历史悠久的筛法，用来找出一定范围内所有的素数。</p>
<p>所使用的原理是从 2 开始，将每个素数的各个倍数，标记成合数。一个素数的各个倍数，是一个差为此素数本身的等差数列。此为这个筛法和试除法不同的关键之处，后者是以素数来测试每个待测数能否被整除。</p>
<p>埃拉托斯特尼筛法是列出所有小素数最有效的方法之一，其名字来自于古希腊数学家埃拉托斯特尼，并且被描述在另一位古希腊数学家尼科马库斯所著的《算术入门》中。</p>
<p>维基百科文章有一个有用的图解解释算法:</p>
<p>请注意,这是一个非常具体的算法,并且测试不会检查您是否实现了算法,只要您已经提出了正确的素数列表.<a href="https://zh.wikipedia.org/wiki/%E5%9F%83%E6%8B%89%E6%89%98%E6%96%AF%E7%89%B9%E5%B0%BC%E7%AD%9B%E6%B3%95">https://zh.wikipedia.org/wiki/埃拉托斯特尼筛法</a></p>
<p>一个好的第一个测试是，检查你不使用除法或余数运算(div, /, mod or % 具体语言所具有的)</p>
<a class="header" href="#资源-34" id="资源-34"><h2>资源</h2></a>
<p>维基百科的 素数 筛<a href="https://zh.wikipedia.org/wiki/%E5%9F%83%E6%8B%89%E6%89%98%E6%96%AF%E7%89%B9%E5%B0%BC%E7%AD%9B%E6%B3%95">https://zh.wikipedia.org/wiki/埃拉托斯特尼筛法</a></p>
<a class="header" href="#2-开始你的表演-44" id="2-开始你的表演-44"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn primes_up_to(upper_bound: u64) -&gt; Vec&lt;u64&gt; {
   unimplemented!(&quot;Construct a vector of all primes up to {}&quot;, upper_bound);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-44" id="3-测试代码查看-44"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn limit_lower_than_the_first_prime() {
   assert_eq!(primes_up_to(1), []);
}

#[test]
//#[ignore]
fn limit_is_the_first_prime() {
   assert_eq!(primes_up_to(2), [2]);
}

#[test]
//#[ignore]
fn primes_up_to_10() {
   assert_eq!(primes_up_to(10), [2, 3, 5, 7]);
}

#[test]
//#[ignore]
fn limit_is_prime() {
   assert_eq!(primes_up_to(13), [2, 3, 5, 7, 11, 13]);
}

#[test]
//#[ignore]
fn limit_of_1000() {
   let expected = vec![
       2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
       97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
       191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
       283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
       401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
       509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619,
       631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743,
       751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
       877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997,
   ];
   assert_eq!(primes_up_to(1000), expected);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-44" id="4-答案-44"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn primes_up_to(limit: i32) -&gt; Vec&lt;i32&gt; {
   let mut integers = (1..limit).map(|x| x + 1).collect::&lt;Vec&lt;i32&gt;&gt;();
   let mut p = Some(2);

   while let Some(y) = p {
       integers.retain(|&amp;x| (x == y) || (x % y != 0));
       p = integers.clone().into_iter().find(|x| *x &gt; y);
   }
   integers
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-44" id="填充相关-44"><h2>填充/相关</h2></a>
<a class="header" href="#rna-transcription" id="rna-transcription"><h1>RNA Transcription</h1></a>
<a class="header" href="#1-readme-45" id="1-readme-45"><h2>1. Readme</h2></a>
<a class="header" href="#rna-转录" id="rna-转录"><h1>RNA 转录</h1></a>
<p>给定 DNA 链,返回其 RNA 补体(每个 RNA 转录).</p>
<p>DNA 和 RNA 链都是核苷酸序列.</p>
<p>DNA 中发现的四个核苷酸是腺嘌呤(<strong>A</strong>),胞嘧啶(<strong>C</strong>),鸟嘌呤(<strong>G</strong>)和胸腺嘧啶(<strong>T</strong>).</p>
<p>RNA 中发现的四个核苷酸是腺嘌呤(<strong>A</strong>),胞嘧啶(<strong>C</strong>),鸟嘌呤(<strong>G</strong>)和尿嘧啶(<strong>T</strong>).</p>
<p>给定 DNA 链,其转录的 RNA 链，通过用其互补物替换每个核苷酸而形成:</p>
<ul>
<li><code>G</code>- &gt;<code>C</code></li>
<li><code>C</code>- &gt;<code>G</code></li>
<li><code>T</code>- &gt;<code>A</code></li>
<li><code>A</code>- &gt;<code>U</code></li>
</ul>
<a class="header" href="#关于-rust-实现的注释" id="关于-rust-实现的注释"><h2>关于 Rust 实现的注释</h2></a>
<p>通过在公共结构中使用私有字段，<code>new</code>函数会返回<code>Option</code>要么<code>Result</code>(在这里<code>DNA::new</code>&amp;<code>RNA::new</code>)，我们可以保证<code>DNA</code>内部的表达是正确的。因为每个有效的 DNA 字符串，都有一个有效的 RNA 字符串,所以我们不需要从<code>to_rna</code>返回一个<code>Result</code>/<code>Option</code>.</p>
<p>这解释了您将在测试中看到的类型签名。</p>
<a class="header" href="#资源-35" id="资源-35"><h2>资源</h2></a>
<p>Hyperphysics<a href="http://hyperphysics.phy-astr.gsu.edu/hbase/Organic/transcription.html">http://hyperphysics.phy-astr.gsu.edu/hbase/Organic/transcription.html</a></p>
<a class="header" href="#2-开始你的表演-45" id="2-开始你的表演-45"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">#[derive(Debug, PartialEq)]
pub struct DNA;

#[derive(Debug, PartialEq)]
pub struct RNA;

impl DNA {
   pub fn new(dna: &amp;str) -&gt; Result&lt;DNA, usize&gt; {
       unimplemented!(&quot;Construct new DNA from '{}' string. If string contains invalid nucleotides return index of first invalid nucleotide&quot;, dna);
   }

   pub fn to_rna(self) -&gt; RNA {
       unimplemented!(&quot;Transform DNA {:?} into corresponding RNA&quot;, self);
   }
}

impl RNA {
   pub fn new(rna: &amp;str) -&gt; Result&lt;RNA, usize&gt; {
       unimplemented!(&quot;Construct new RNA from '{}' string. If string contains invalid nucleotides return index of first invalid nucleotide&quot;, rna);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-45" id="3-测试代码查看-45"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_valid_dna_input() {
   assert!(DNA::new(&quot;GCTA&quot;).is_ok());
}

#[test]
//#[ignore]
fn test_valid_rna_input() {
   assert!(RNA::new(&quot;CGAU&quot;).is_ok());
}

#[test]
//#[ignore]
fn test_invalid_dna_input() {
   // Invalid character
   assert_eq!(DNA::new(&quot;X&quot;).err(), Some(0));
   // Valid nucleotide, but invalid in context
   assert_eq!(DNA::new(&quot;U&quot;).err(), Some(0));
   // Longer string with contained errors
   assert_eq!(DNA::new(&quot;ACGTUXXCTTAA&quot;).err(), Some(4));
}

#[test]
//#[ignore]
fn test_invalid_rna_input() {
   // Invalid character
   assert!(RNA::new(&quot;X&quot;).is_err());
   // Valid nucleotide, but invalid in context
   assert!(RNA::new(&quot;T&quot;).is_err());
   // Longer string with contained errors
   assert!(RNA::new(&quot;ACGUTTXCUUAA&quot;).is_err());
}

#[test]
//#[ignore]
fn test_acid_equals_acid() {
   assert_eq!(DNA::new(&quot;CGA&quot;).unwrap(), DNA::new(&quot;CGA&quot;).unwrap());
   assert_ne!(DNA::new(&quot;CGA&quot;).unwrap(), DNA::new(&quot;AGC&quot;).unwrap());
   assert_eq!(RNA::new(&quot;CGA&quot;).unwrap(), RNA::new(&quot;CGA&quot;).unwrap());
   assert_ne!(RNA::new(&quot;CGA&quot;).unwrap(), RNA::new(&quot;AGC&quot;).unwrap());
}

#[test]
//#[ignore]
fn test_transcribes_cytosine_guanine() {
   assert_eq!(RNA::new(&quot;G&quot;).unwrap(), DNA::new(&quot;C&quot;).unwrap().to_rna());
}

#[test]
//#[ignore]
fn test_transcribes_guanine_cytosine() {
   assert_eq!(RNA::new(&quot;C&quot;).unwrap(), DNA::new(&quot;G&quot;).unwrap().to_rna());
}

#[test]
//#[ignore]
fn test_transcribes_adenine_uracil() {
   assert_eq!(RNA::new(&quot;U&quot;).unwrap(), DNA::new(&quot;A&quot;).unwrap().to_rna());
}

#[test]
//#[ignore]
fn test_transcribes_thymine_to_adenine() {
   assert_eq!(RNA::new(&quot;A&quot;).unwrap(), DNA::new(&quot;T&quot;).unwrap().to_rna());
}

#[test]
//#[ignore]
fn test_transcribes_all_dna_to_rna() {
   assert_eq!(
       RNA::new(&quot;UGCACCAGAAUU&quot;).unwrap(),
       DNA::new(&quot;ACGTGGTCTTAA&quot;).unwrap().to_rna()
   )
}

#}</code></pre></pre>
<a class="header" href="#4-答案-45" id="4-答案-45"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
/// The possible nucleotides in DNA and RNA
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum Nucleotide {
   Adenine,
   Cytosine,
   Guanine,
   Thymine,
   Uracil,
}

impl Nucleotide {
   /// Parses a nucleotide from its character value, if valid.
   fn from_char(ch: char) -&gt; Option&lt;Nucleotide&gt; {
       Some(match ch {
           'A' =&gt; Nucleotide::Adenine,
           'C' =&gt; Nucleotide::Cytosine,
           'G' =&gt; Nucleotide::Guanine,
           'T' =&gt; Nucleotide::Thymine,
           'U' =&gt; Nucleotide::Uracil,
           _ =&gt; {
               return None;
           }
       })
   }
}

/// A vector of nucleotides
///
/// Guaranteed that Uracil is not present thanks to `new`.
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct DNA(Vec&lt;Nucleotide&gt;);

impl DNA {
   /// Parse a DNA string, checking it is valid.
   ///
   /// The error value is the first invalid character index (char index, not utf8).
   pub fn new(input: &amp;str) -&gt; Result&lt;DNA, usize&gt; {
       let mut out = Vec::new();
       for (idx, ch) in input.chars().enumerate() {
           match Nucleotide::from_char(ch) {
               Some(Nucleotide::Uracil) | None =&gt; {
                   return Err(idx);
               }
               Some(n) =&gt; {
                   out.push(n);
               }
           }
       }
       Ok(DNA(out))
   }

   pub fn to_rna(mut self) -&gt; RNA {
       for nuc in self.0.iter_mut() {
           *nuc = match *nuc {
               Nucleotide::Adenine =&gt; Nucleotide::Uracil,
               Nucleotide::Cytosine =&gt; Nucleotide::Guanine,
               Nucleotide::Guanine =&gt; Nucleotide::Cytosine,
               Nucleotide::Thymine =&gt; Nucleotide::Adenine,
               Nucleotide::Uracil =&gt; unreachable!(),
           }
       }
       RNA(self.0)
   }
}

#[derive(Debug, Eq, PartialEq, Clone)]
pub struct RNA(Vec&lt;Nucleotide&gt;);

impl RNA {
   /// Parse a RNA string, checking it is valid.
   ///
   /// The error value is the first invalid character index (char index, not utf8).
   pub fn new(input: &amp;str) -&gt; Result&lt;RNA, usize&gt; {
       let mut out = Vec::new();
       for (idx, ch) in input.chars().enumerate() {
           match Nucleotide::from_char(ch) {
               Some(Nucleotide::Thymine) | None =&gt; {
                   return Err(idx);
               }
               Some(n) =&gt; {
                   out.push(n);
               }
           }
       }
       Ok(RNA(out))
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-45" id="填充相关-45"><h2>填充/相关</h2></a>
<a class="header" href="#triangle" id="triangle"><h1>Triangle</h1></a>
<a class="header" href="#1-readme-46" id="1-readme-46"><h2>1. Readme</h2></a>
<a class="header" href="#三角形" id="三角形"><h1>三角形</h1></a>
<p>确定三角形是等边、等腰还是不等边三角形.</p>
<p>一个<em>等边的</em>三角形，三条边都有相同的长度。</p>
<p>一个<em>等腰的</em>三角形，至少两边相同的长度。(有时它被指定为两边长度完全相同,但是为了这个练习的目的，我们的说法是，至少两边。)</p>
<p>一<em>不等边的</em>三角形的两边各有不同的长度。</p>
<a class="header" href="#笔记-2" id="笔记-2"><h2>笔记</h2></a>
<p>为了能形成三角形，所有的边都必须的长度&gt;0，并且任何两边的长度之和必须大于或等于第三边的长度。见<a href="https://en.wikipedia.org/wiki/Triangle_inequality">不等三角形</a>.</p>
<a class="header" href="#挖深点" id="挖深点"><h2>挖深点</h2></a>
<p>两边长度之和，是<em>等于</em>第三边，就叫做<em>退化</em>三角形 - 因它有零面积，看起来像一条直线。随意添加你自己的代码/测试来检查退化三角形.</p>
<a class="header" href="#rust-中-三角形帮助" id="rust-中-三角形帮助"><h1>Rust 中 三角形帮助</h1></a>
<ul>
<li><a href="https://doc.rust-lang.org/std/result/index.html">Result</a></li>
</ul>
<p>实现这一点可以采取多种形式。以下是一些可以帮助你的话题，这取决于你采取的方法.</p>
<ul>
<li><a href="https://doc.rust-lang.org/book/ch06-00-enums.html">Enums</a></li>
<li><a href="https://doc.rust-lang.org/book/ch10-02-traits.html">Traits</a></li>
<li><a href="https://doc.rust-lang.org/std/collections/btree_set/struct.BTreeSet.html">BTreeSet</a></li>
</ul>
<p>或者也许你会想出一种不用那些方法的方法!</p>
<a class="header" href="#非整数长度" id="非整数长度"><h2>非整数长度</h2></a>
<p>基础练习测试三角形的边，都是整数的识别。然而，一些三角形不能用纯整数表示。一个简单的例子是一个直角三角形(也是等边三角形，两等边分开 90 度)，其等边都有 1 的长度。它的斜边是 2 的平方根，这是一个无理数: 没有简单的乘法，可以将这个数表示为整数。</p>
<p>重写分析函数来处理整数和浮点情况，老乏味啦，特别是对于所有潜在的整数和浮点类型的情况来说：如给定的 8, 16, 32、64 和 128 位宽度的已签名和未签名的变体，甚至再考虑浮点数，就多出了 10 个根本上相同的代码,!</p>
<p>这有个更好的方法:<a href="https://doc.rust-lang.org/stable/book/2018-edition/ch10-00-generics.html">generics</a>。 把你的三角形重写为<code>Triangle&lt;T&gt;</code>，这样您就可以编写一次代码，并将生成所有这些专门化的工作交给编译器。注意，为了使用数学运算，您需要将泛型类型限制为，支持使用特征的那些运算的类型。</p>
<p>有些加分测试，这些测试，能测试您在浮点数字上的实现。若要启用它们,请使用<code>generic</code>特征标记，像这样:</p>
<pre><code class="language-bash">cargo test --features generic
</code></pre>
<a class="header" href="#资源-36" id="资源-36"><h2>资源</h2></a>
<p>Ruby-科恩三角形项目,第 1 和 2 部分<a href="http://rubykoans.com">http://rubykoans.com</a></p>
<a class="header" href="#2-开始你的表演-46" id="2-开始你的表演-46"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub struct Triangle;

impl Triangle {
   pub fn build(sides: [u64; 3]) -&gt; Option&lt;Triangle&gt; {
       unimplemented!(&quot;Construct new Triangle from following sides: {:?}. Return None if the sides are invalid.&quot;, sides);
   }

   pub fn is_equilateral(&amp;self) -&gt; bool {
       unimplemented!(&quot;Determine if the Triangle is equilateral.&quot;);
   }

   pub fn is_scalene(&amp;self) -&gt; bool {
       unimplemented!(&quot;Determine if the Triangle is scalene.&quot;);
   }

   pub fn is_isosceles(&amp;self) -&gt; bool {
       unimplemented!(&quot;Determine if the Triangle is isosceles.&quot;);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-46" id="3-测试代码查看-46"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn positive_length_sides_are_ok() {
   let sides = [2, 2, 2];
   let triangle = Triangle::build(sides);
   assert!(triangle.is_some());
}

#[test]
//#[ignore]
fn zero_length_sides_are_illegal() {
   let sides = [0, 0, 0];
   let triangle = Triangle::build(sides);
   assert!(triangle.is_none());
}

#[test]
//#[ignore]
fn equilateral_triangles_have_equal_sides() {
   let sides = [2, 2, 2];
   let triangle = Triangle::build(sides).unwrap();
   assert!(triangle.is_equilateral());
   assert!(!triangle.is_scalene());
}

#[test]
//#[ignore]
fn larger_equilateral_triangles_have_equal_sides() {
   let sides = [10, 10, 10];
   let triangle = Triangle::build(sides).unwrap();
   assert!(triangle.is_equilateral());
   assert!(!triangle.is_scalene());
}

#[test]
//#[ignore]
fn isosceles_triangles_have_two_equal_sides_one() {
   let sides = [3, 4, 4];
   let triangle = Triangle::build(sides).unwrap();
   assert!(!triangle.is_equilateral());
   assert!(triangle.is_isosceles());
   assert!(!triangle.is_scalene());
}

#[test]
//#[ignore]
fn isosceles_triangles_have_two_equal_sides_two() {
   let sides = [4, 4, 3];
   let triangle = Triangle::build(sides).unwrap();
   assert!(!triangle.is_equilateral());
   assert!(triangle.is_isosceles());
   assert!(!triangle.is_scalene());
}

#[test]
//#[ignore]
fn isosceles_triangles_have_two_equal_sides_three() {
   let sides = [4, 3, 4];
   let triangle = Triangle::build(sides).unwrap();
   assert!(!triangle.is_equilateral());
   assert!(triangle.is_isosceles());
   assert!(!triangle.is_scalene());
}

#[test]
//#[ignore]
fn isosceles_triangles_have_two_equal_sides_four() {
   let sides = [4, 7, 4];
   let triangle = Triangle::build(sides).unwrap();
   assert!(!triangle.is_equilateral());
   assert!(triangle.is_isosceles());
   assert!(!triangle.is_scalene());
}

#[test]
//#[ignore]
fn scalene_triangle_has_no_equal_sides_one() {
   let sides = [3, 4, 5];
   let triangle = Triangle::build(sides).unwrap();
   assert!(!triangle.is_equilateral());
   assert!(!triangle.is_isosceles());
   assert!(triangle.is_scalene());
}

#[test]
//#[ignore]
fn scalene_triangle_has_no_equal_sides_two() {
   let sides = [5, 4, 6];
   let triangle = Triangle::build(sides).unwrap();
   assert!(!triangle.is_equilateral());
   assert!(!triangle.is_isosceles());
   assert!(triangle.is_scalene());
}

#[test]
//#[ignore]
fn scalene_triangle_has_no_equal_sides_three() {
   let sides = [10, 11, 12];
   let triangle = Triangle::build(sides).unwrap();
   assert!(!triangle.is_equilateral());
   assert!(!triangle.is_isosceles());
   assert!(triangle.is_scalene());
}

#[test]
//#[ignore]
fn scalene_triangle_has_no_equal_sides_four() {
   let sides = [5, 4, 2];
   let triangle = Triangle::build(sides).unwrap();
   assert!(!triangle.is_equilateral());
   assert!(!triangle.is_isosceles());
   assert!(triangle.is_scalene());
}

#[test]
//#[ignore]
fn sum_of_two_sides_must_equal_or_exceed_the_remaining_side_one() {
   let sides = [7, 3, 2];
   let triangle = Triangle::build(sides);
   assert!(triangle.is_none());
}

#[test]
//#[ignore]
fn sum_of_two_sides_must_equal_or_exceed_the_remaining_side_two() {
   let sides = [1, 1, 3];
   let triangle = Triangle::build(sides);
   assert!(triangle.is_none());
}

#[test]
//#[ignore]
#[cfg(feature = &quot;generic&quot;)]
fn scalene_triangle_with_floating_point_sides() {
   let sides = [0.4, 0.6, 0.3];
   let triangle = Triangle::build(sides).unwrap();
   assert!(!triangle.is_equilateral());
   assert!(!triangle.is_isosceles());
   assert!(triangle.is_scalene());
}

#[test]
//#[ignore]
#[cfg(feature = &quot;generic&quot;)]
fn equilateral_triangles_with_floating_point_sides() {
   let sides = [0.2, 0.2, 0.2];
   let triangle = Triangle::build(sides).unwrap();
   assert!(triangle.is_equilateral());
   assert!(!triangle.is_scalene());
}

#[test]
//#[ignore]
#[cfg(feature = &quot;generic&quot;)]
fn isosceles_triangle_with_floating_point_sides() {
   let sides = [0.3, 0.4, 0.4];
   let triangle = Triangle::build(sides).unwrap();
   assert!(!triangle.is_equilateral());
   assert!(triangle.is_isosceles());
   assert!(!triangle.is_scalene());
}

#}</code></pre></pre>
<a class="header" href="#4-答案-46" id="4-答案-46"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::ops::Add;

pub struct Triangle&lt;T&gt; {
   sides: [T; 3],
}

impl&lt;T&gt; Triangle&lt;T&gt;
where
   T: Copy + PartialEq + PartialOrd + Add&lt;Output = T&gt; + Default,
{
   fn valid_sides(&amp;self) -&gt; bool {
       (self.sides.iter().all(|&amp;s| s &gt; T::default()))
           &amp;&amp; (self.sides[0] + self.sides[1] &gt;= self.sides[2])
           &amp;&amp; (self.sides[1] + self.sides[2] &gt;= self.sides[0])
           &amp;&amp; (self.sides[2] + self.sides[0] &gt;= self.sides[1])
   }

   fn count_distinct_pairs(&amp;self) -&gt; usize {
       [(0, 1), (0, 2), (1, 2)]
           .iter()
           .map(|&amp;(a, b)| if self.sides[a] != self.sides[b] { 1 } else { 0 })
           .sum()
   }

   pub fn build(sides: [T; 3]) -&gt; Option&lt;Triangle&lt;T&gt;&gt; {
       let t = Triangle { sides: sides };

       if t.valid_sides() {
           Some(t)
       } else {
           None
       }
   }

   pub fn is_equilateral(&amp;self) -&gt; bool {
       self.count_distinct_pairs() == 0
   }

   pub fn is_isosceles(&amp;self) -&gt; bool {
       self.count_distinct_pairs() == 2
   }

   pub fn is_scalene(&amp;self) -&gt; bool {
       self.count_distinct_pairs() == 3
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-46" id="填充相关-46"><h2>填充/相关</h2></a>
<a class="header" href="#roman-numerals" id="roman-numerals"><h1>Roman Numerals</h1></a>
<a class="header" href="#1-readme-47" id="1-readme-47"><h2>1. Readme</h2></a>
<a class="header" href="#罗马数字" id="罗马数字"><h1>罗马数字</h1></a>
<p>写一个函数,从普通数字，转换成罗马数字.</p>
<p>罗马人是一群聪明的人。他们征服了欧洲大部分国家,统治了几百年。他们发明了混凝土和直路,甚至 Bikinis 夜店。他们从来没有发现过的一件事就是数字零。这使得写作和约会他们的功绩的广泛历史稍有挑战性，但他们提出的数字系统仍在使用。例如,英国广播公司使用罗马数字制定他们的节目。</p>
<p>罗马人用字母 I（1）、V（5）、X（10）、L（50）、C（100）、D（500）和 M（1000） 写数字(注意这些字母有很多直线,因此很容易侵入石碑)。</p>
<pre><code class="language-text"> 1  =&gt; I
10  =&gt; X
 7  =&gt; VII
</code></pre>
<blockquote>
<p>不需要能 转换 超过 3000 的罗马数字</p>
</blockquote>
<p>在较大的罗马数字的右边记上较小的罗马数字，表示大数字加小数字。
在较大的罗马数字的左边记上较小的罗马数字，表示大数字减小数字。</p>
<p>要在实践中看到这一点,请考虑 1990 的例子.</p>
<p>在罗马数字中,1990 是 MCMXC:</p>
<p>1000=M 900=CM 90=XC</p>
<blockquote>
<p>CM = 1000 - 100 = 900</p>
</blockquote>
<p>2008 被写成 MMVIII:</p>
<p>2000=MM 8=Ⅷ</p>
<p>参见:<a href="http://www.novaroma.org/via_romana/numbers.html">http://www.novaroma.org/via_romana/numbers.html</a></p>
<a class="header" href="#资源-37" id="资源-37"><h2>资源</h2></a>
<p>维基百科<a href="https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97">https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97</a></p>
<a class="header" href="#2-开始你的表演-47" id="2-开始你的表演-47"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::fmt::{Display, Formatter, Result};

pub struct Roman;

impl Display for Roman {
   fn fmt(&amp;self, _f: &amp;mut Formatter) -&gt; Result {
       unimplemented!(&quot;Return a roman-numeral string representation of the Roman object&quot;);
   }
}

impl From&lt;u32&gt; for Roman {
   fn from(num: u32) -&gt; Self {
       unimplemented!(&quot;Construct a Roman object from the '{}' number&quot;, num);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-47" id="3-测试代码查看-47"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_one() {
   assert_eq!(&quot;I&quot;, Roman::from(1).to_string());
}

#[test]
//#[ignore]
fn test_two() {
   assert_eq!(&quot;II&quot;, Roman::from(2).to_string());
}

#[test]
//#[ignore]
fn test_three() {
   assert_eq!(&quot;III&quot;, Roman::from(3).to_string());
}

#[test]
//#[ignore]
fn test_four() {
   assert_eq!(&quot;IV&quot;, Roman::from(4).to_string());
}

#[test]
//#[ignore]
fn test_five() {
   assert_eq!(&quot;V&quot;, Roman::from(5).to_string());
}

#[test]
//#[ignore]
fn test_six() {
   assert_eq!(&quot;VI&quot;, Roman::from(6).to_string());
}

#[test]
//#[ignore]
fn test_nine() {
   assert_eq!(&quot;IX&quot;, Roman::from(9).to_string());
}

#[test]
//#[ignore]
fn test_twenty_seven() {
   assert_eq!(&quot;XXVII&quot;, Roman::from(27).to_string());
}

#[test]
//#[ignore]
fn test_forty_eight() {
   assert_eq!(&quot;XLVIII&quot;, Roman::from(48).to_string());
}

#[test]
//#[ignore]
fn test_fifty_nine() {
   assert_eq!(&quot;LIX&quot;, Roman::from(59).to_string());
}

#[test]
//#[ignore]
fn test_ninety_three() {
   assert_eq!(&quot;XCIII&quot;, Roman::from(93).to_string());
}

#[test]
//#[ignore]
fn test_141() {
   assert_eq!(&quot;CXLI&quot;, Roman::from(141).to_string());
}

#[test]
//#[ignore]
fn test_163() {
   assert_eq!(&quot;CLXIII&quot;, Roman::from(163).to_string());
}

#[test]
//#[ignore]
fn test_402() {
   assert_eq!(&quot;CDII&quot;, Roman::from(402).to_string());
}

#[test]
//#[ignore]
fn test_575() {
   assert_eq!(&quot;DLXXV&quot;, Roman::from(575).to_string());
}

#[test]
//#[ignore]
fn test_911() {
   assert_eq!(&quot;CMXI&quot;, Roman::from(911).to_string());
}

#[test]
//#[ignore]
fn test_1024() {
   assert_eq!(&quot;MXXIV&quot;, Roman::from(1024).to_string());
}

#[test]
//#[ignore]
fn test_3000() {
   assert_eq!(&quot;MMM&quot;, Roman::from(3000).to_string());
}

#}</code></pre></pre>
<a class="header" href="#4-答案-47" id="4-答案-47"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::fmt;

static ROMAN_MAP: [(usize, &amp;'static str); 13] = [
   (1, &quot;I&quot;),
   (4, &quot;IV&quot;),
   (5, &quot;V&quot;),
   (9, &quot;IX&quot;),
   (10, &quot;X&quot;),
   (40, &quot;XL&quot;),
   (50, &quot;L&quot;),
   (90, &quot;XC&quot;),
   (100, &quot;C&quot;),
   (400, &quot;CD&quot;),
   (500, &quot;D&quot;),
   (900, &quot;CM&quot;),
   (1000, &quot;M&quot;),
];

pub struct Roman {
   num: usize,
}

impl From&lt;usize&gt; for Roman {
   fn from(i: usize) -&gt; Self {
       Roman::new(i)
   }
}

impl fmt::Display for Roman {
   fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
       let mut start = self.num.clone();
       let mut result = String::new();
       for &amp;(numeric, roman_string) in ROMAN_MAP.into_iter().rev() {
           while start &gt;= numeric {
               result.push_str(roman_string);
               start = start - numeric;
           }
       }
       write!(f, &quot;{}&quot;, result)
   }
}

impl Roman {
   fn new(num: usize) -&gt; Roman {
       Roman { num: num }
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-47" id="填充相关-47"><h2>填充/相关</h2></a>
<a class="header" href="#all-your-base" id="all-your-base"><h1>All Your Base</h1></a>
<a class="header" href="#1-readme-48" id="1-readme-48"><h2>1. Readme</h2></a>
<a class="header" href="#你的所有基本" id="你的所有基本"><h1>你的所有基本</h1></a>
<p>将一个数字，表示为一个基数中的数字序列，并转为其他基本</p>
<p>实施通用基本转换。给出一个<strong>a</strong>参数，表示为数字序列，将其转换为基数<strong>b</strong>。</p>
<a class="header" href="#笔记-3" id="笔记-3"><h2>笔记</h2></a>
<ul>
<li>尝试自己实现转换。请勿使用其他内容为您执行转换.</li>
</ul>
<a class="header" href="#关于a-hrefhttpsenwikipediaorgwikipositional_notation位置表示法a" id="关于a-hrefhttpsenwikipediaorgwikipositional_notation位置表示法a"><h2>关于<a href="https://en.wikipedia.org/wiki/Positional_notation">位置表示法</a></h2></a>
<p>在位置表示法中，以数字表示<strong>b</strong>可以被理解为权力的线性组合<strong>b</strong>.</p>
<p>数字 42，<em>基本为 10</em>，意思是:</p>
<p><code>(4 * 10^1) + (2 * 10^0)</code></p>
<p>数字 101010，<em>基本为 2</em>，意思是:</p>
<p><code>(1 * 2^5) + (0 * 2^4) + (1 * 2^3) + (0 * 2^2) + (1 * 2^1) + (0 * 2^0)</code></p>
<p>号码 1120，<em>基本为 3</em>，意思是:</p>
<p><code>(1 * 3^3) + (1 * 3^2) + (2 * 3^1) + (0 * 3^0)</code></p>
<p>我想你明白了!</p>
<p><em>是。上面这三个数字完全一样。恭喜!</em></p>
<a class="header" href="#2-开始你的表演-48" id="2-开始你的表演-48"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">#[derive(Debug, PartialEq)]
pub enum Error {
   InvalidInputBase,
   InvalidOutputBase,
   InvalidDigit(u32),
}

///
/// Convert a number between two bases.
///
/// A number is any slice of digits.
/// A digit is any unsigned integer (e.g. u8, u16, u32, u64, or usize).
/// Bases are specified as unsigned integers.
///
/// Return an `Err(.)` if the conversion is impossible.
/// The tests do not test for specific values inside the `Err(.)`.
///
///
/// You are allowed to change the function signature as long as all test still pass.
///
///
/// Example:
/// Input
///   number: &amp;[4, 2]
///   from_base: 10
///   to_base: 2
/// Result
///   Ok(vec![1, 0, 1, 0, 1, 0])
///
/// The example corresponds to converting the number 42 from decimal
/// which is equivalent to 101010 in binary.
///
///
/// Notes:
///  * The empty slice ( &quot;[]&quot; ) is equal to the number 0.
///  * Never output leading 0 digits. However, your function must be able to
///     process input with leading 0 digits.
///
pub fn convert(number: &amp;[u32], from_base: u32, to_base: u32) -&gt; Result&lt;Vec&lt;u32&gt;, Error&gt; {
   unimplemented!(
       &quot;Convert {:?} from base {} to base {}&quot;,
       number,
       from_base,
       to_base
   )
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-48" id="3-测试代码查看-48"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn single_bit_one_to_decimal() {
   let input_base = 2;
   let input_digits = &amp;[1];
   let output_base = 10;
   let output_digits = vec![1];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn binary_to_single_decimal() {
   let input_base = 2;
   let input_digits = &amp;[1, 0, 1];
   let output_base = 10;
   let output_digits = vec![5];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn single_decimal_to_binary() {
   let input_base = 10;
   let input_digits = &amp;[5];
   let output_base = 2;
   let output_digits = vec![1, 0, 1];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn binary_to_multiple_decimal() {
   let input_base = 2;
   let input_digits = &amp;[1, 0, 1, 0, 1, 0];
   let output_base = 10;
   let output_digits = vec![4, 2];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn decimal_to_binary() {
   let input_base = 10;
   let input_digits = &amp;[4, 2];
   let output_base = 2;
   let output_digits = vec![1, 0, 1, 0, 1, 0];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn trinary_to_hexadecimal() {
   let input_base = 3;
   let input_digits = &amp;[1, 1, 2, 0];
   let output_base = 16;
   let output_digits = vec![2, 10];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn hexadecimal_to_trinary() {
   let input_base = 16;
   let input_digits = &amp;[2, 10];
   let output_base = 3;
   let output_digits = vec![1, 1, 2, 0];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn fifteen_bit_integer() {
   let input_base = 97;
   let input_digits = &amp;[3, 46, 60];
   let output_base = 73;
   let output_digits = vec![6, 10, 45];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn empty_list() {
   let input_base = 2;
   let input_digits = &amp;[];
   let output_base = 10;
   let output_digits = vec![];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn single_zero() {
   let input_base = 10;
   let input_digits = &amp;[0];
   let output_base = 2;
   let output_digits = vec![];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn multiple_zeros() {
   let input_base = 10;
   let input_digits = &amp;[0, 0, 0];
   let output_base = 2;
   let output_digits = vec![];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn leading_zeros() {
   let input_base = 7;
   let input_digits = &amp;[0, 6, 0];
   let output_base = 10;
   let output_digits = vec![4, 2];
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Ok(output_digits)
   );
}

#[test]
//#[ignore]
fn invalid_positive_digit() {
   let input_base = 2;
   let input_digits = &amp;[1, 2, 1, 0, 1, 0];
   let output_base = 10;
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Err(Error::InvalidDigit(2))
   );
}

#[test]
//#[ignore]
fn input_base_is_one() {
   let input_base = 1;
   let input_digits = &amp;[];
   let output_base = 10;
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Err(Error::InvalidInputBase)
   );
}

#[test]
//#[ignore]
fn output_base_is_one() {
   let input_base = 2;
   let input_digits = &amp;[1, 0, 1, 0, 1, 0];
   let output_base = 1;
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Err(Error::InvalidOutputBase)
   );
}

#[test]
//#[ignore]
fn input_base_is_zero() {
   let input_base = 0;
   let input_digits = &amp;[];
   let output_base = 10;
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Err(Error::InvalidInputBase)
   );
}

#[test]
//#[ignore]
fn output_base_is_zero() {
   let input_base = 10;
   let input_digits = &amp;[7];
   let output_base = 0;
   assert_eq!(
       convert(input_digits, input_base, output_base),
       Err(Error::InvalidOutputBase)
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-48" id="4-答案-48"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub type Digit = u32;

#[derive(Debug, PartialEq)]
pub enum Error {
   InvalidInputBase,
   InvalidOutputBase,
   InvalidDigit(Digit),
}

///
/// Convert a number between two bases.
///
/// A number is any slice of digits.
/// A digit is any unsigned integer (e.g. u8, u16, u32, u64, or usize).
/// Bases are specified as unsigned integers.
///
/// Return an `Err(.)` if the conversion is impossible.
/// The tests do not test for specific values inside the `Err(.)`.
///
///
/// You are allowed to change the function signature as long as all test still pass.
///
///
/// Example:
/// Input
///   number: &amp;[4, 2]
///   from_base: 10
///   to_base: 2
/// Result
///   Ok(vec![1, 0, 1, 0, 1, 0])
///
/// The example corresponds to converting the number 42 from decimal
/// which is equivalent to 101010 in binary.
///
///
/// Notes:
///  * The empty slice ( &quot;[]&quot; ) is equal to the number 0.
///  * Never output leading 0 digits. However, your function must be able to
///     process input with leading 0 digits.
///
pub fn convert&lt;P: AsRef&lt;[Digit]&gt;&gt;(
   digits: P,
   from_base: Digit,
   to_base: Digit,
) -&gt; Result&lt;Vec&lt;Digit&gt;, Error&gt; {
   // check that both bases are in the correct range
   if from_base &lt; 2 {
       return Err(Error::InvalidInputBase);
   }
   if to_base &lt; 2 {
       return Err(Error::InvalidOutputBase);
   }

   // check that all digits are in the correct range specified by the base
   if let Some(&amp;invalid) = digits.as_ref().iter().find(|&amp;num| *num &gt;= from_base) {
       return Err(Error::InvalidDigit(invalid));
   }

   // convert all digits into a single large number
   let mut immediate = digits
       .as_ref()
       .iter()
       .rev()
       .enumerate()
       .map(|(i, &amp;num)| num * from_base.pow(i as u32))
       .fold(0, |accu, num| accu + num);

   // convert number into digits
   let mut res = Vec::new();
   while immediate &gt; 0 {
       res.push(immediate % to_base);
       immediate /= to_base;
   }
   // fix order of digits
   res.reverse();
   Ok(res)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-48" id="填充相关-48"><h2>填充/相关</h2></a>
<a class="header" href="#grade-school" id="grade-school"><h1>Grade School</h1></a>
<a class="header" href="#1-readme-49" id="1-readme-49"><h2>1. Readme</h2></a>
<a class="header" href="#学级" id="学级"><h1>学级</h1></a>
<p>根据学生的姓名以及他们所处的年级，为学校创建一个名册.</p>
<p>最后，你应该能够:</p>
<ul>
<li>将学生的姓名添加到年级名册
<ul>
<li>“Add Jim to grade 2.”</li>
<li>“OK.”</li>
</ul>
</li>
<li>获取所有注册年级的学生列表
<ul>
<li>“哪个学生在二年级?”</li>
<li>“We’ve only got Jim just now.”</li>
</ul>
</li>
<li>获取所有年级所有学生的排序列表。年级应分为 1，2，3 级，年级中的学生应按名称按字母顺序排序。
<ul>
<li>“谁现在都在学校就读?”
<ul>
<li>“Grade 1: Anna, Barb, and Charlie. Grade 2: Alex, Peter, and Zoe.
Grade 3…”</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>请注意，我们所有学生只有一个名字.(这是一个小镇，你想要什么?)</p>
<a class="header" href="#加分-3" id="加分-3"><h2>加分</h2></a>
<p>你是否通过了测试，且代码干净了?如果您愿意，可以尝试以下一些额外的事情:</p>
<ul>
<li>如果您使用的语言具有可变数据结构，并且您的实现，会不会让外部代码，能直接改变学校的内部数据库，请查看是否可以阻止这种情况。随意尝试其他测试.</li>
</ul>
<a class="header" href="#资源-38" id="资源-38"><h2>资源</h2></a>
<p>与 gSchool 的 Phil Battos 进行配对<a href="http://gschool.it">http://gschool.it</a></p>
<a class="header" href="#2-开始你的表演-49" id="2-开始你的表演-49"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub struct School {}

impl School {
   pub fn new() -&gt; School {
       unimplemented!()
   }

   pub fn add(&amp;mut self, grade: u32, student: &amp;str) {
       unimplemented!(&quot;Add {} to the roster for {}&quot;, student, grade)
   }

   pub fn grades(&amp;self) -&gt; Vec&lt;u32&gt; {
       unimplemented!()
   }

   // If grade returned an `Option&lt;&amp;Vec&lt;String&gt;&gt;`,
   // the internal implementation would be forced to keep a `Vec&lt;String&gt;` to lend out.
   // By returning an owned vector instead,
   // the internal implementation is free to use whatever it chooses.
   pub fn grade(&amp;self, grade: u32) -&gt; Option&lt;Vec&lt;String&gt;&gt; {
       unimplemented!(&quot;Return the list of students in {}&quot;, grade)
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-49" id="3-测试代码查看-49"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn some_strings(v: &amp;[&amp;str]) -&gt; Option&lt;Vec&lt;String&gt;&gt; {
   Some(v.iter().map(|s| s.to_string()).collect())
}

#[test]
fn test_grades_for_empty_school() {
   let s = School::new();
   assert_eq!(s.grades(), vec![]);
}

#[test]
//#[ignore]
fn test_grades_for_one_student() {
   let mut s = School::new();
   s.add(2, &quot;Aimee&quot;);
   assert_eq!(s.grades(), vec![2]);
}

#[test]
//#[ignore]
fn test_grades_for_several_students_are_sorted() {
   let mut s = School::new();
   s.add(2, &quot;Aimee&quot;);
   s.add(7, &quot;Logan&quot;);
   s.add(4, &quot;Blair&quot;);
   assert_eq!(s.grades(), vec![2, 4, 7]);
}

#[test]
//#[ignore]
fn test_grades_when_several_students_have_the_same_grade() {
   let mut s = School::new();
   s.add(2, &quot;Aimee&quot;);
   s.add(2, &quot;Logan&quot;);
   s.add(2, &quot;Blair&quot;);
   assert_eq!(s.grades(), vec![2]);
}

#[test]
//#[ignore]
fn test_grade_for_empty_school() {
   let s = School::new();
   assert_eq!(s.grade(1), None);
}

#[test]
//#[ignore]
fn test_grade_when_no_students_have_that_grade() {
   let mut s = School::new();
   s.add(7, &quot;Logan&quot;);
   assert_eq!(s.grade(1), None);
}

#[test]
//#[ignore]
fn test_grade_for_one_student() {
   let mut s = School::new();
   s.add(2, &quot;Aimee&quot;);
   assert_eq!(s.grade(2), some_strings(&amp;[&quot;Aimee&quot;]));
}

#[test]
//#[ignore]
fn test_grade_returns_students_sorted_by_name() {
   let mut s = School::new();
   s.add(2, &quot;James&quot;);
   s.add(2, &quot;Blair&quot;);
   s.add(2, &quot;Paul&quot;);
   assert_eq!(s.grade(2), some_strings(&amp;[&quot;Blair&quot;, &quot;James&quot;, &quot;Paul&quot;]));
}

#[test]
//#[ignore]
fn test_add_students_to_different_grades() {
   let mut s = School::new();
   s.add(3, &quot;Chelsea&quot;);
   s.add(7, &quot;Logan&quot;);
   assert_eq!(s.grades(), vec![3, 7]);
   assert_eq!(s.grade(3), some_strings(&amp;[&quot;Chelsea&quot;]));
   assert_eq!(s.grade(7), some_strings(&amp;[&quot;Logan&quot;]));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-49" id="4-答案-49"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;

pub struct School {
   grades: HashMap&lt;u32, Vec&lt;String&gt;&gt;,
}

impl School {
   pub fn new() -&gt; School {
       School {
           grades: HashMap::new(),
       }
   }

   pub fn add(&amp;mut self, grade: u32, student: &amp;str) {
       let entry = self.grades.entry(grade).or_insert(Vec::new());
       entry.push(student.to_string());
       entry.sort();
   }

   pub fn grades(&amp;self) -&gt; Vec&lt;u32&gt; {
       let mut s = self.grades.keys().cloned().collect::&lt;Vec&lt;u32&gt;&gt;();
       s.sort();
       s
   }

   pub fn grade(&amp;self, grade: u32) -&gt; Option&lt;Vec&lt;String&gt;&gt; {
       self.grades.get(&amp;grade).map(|v| v.iter().cloned().collect())
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-49" id="填充相关-49"><h2>填充/相关</h2></a>
<a class="header" href="#binary-search" id="binary-search"><h1>Binary Search</h1></a>
<a class="header" href="#1-readme-50" id="1-readme-50"><h2>1. Readme</h2></a>
<a class="header" href="#二分查找" id="二分查找"><h1>二分查找</h1></a>
<p>实现二分查找算法.</p>
<p>搜索已排序的集合是一项常见任务。字典是定义单词的排序列表。有了一个词，就可以找到它的定义。电话簿是人员姓名，地址和电话号码的分类列表。知道某人的姓名可以让他们快速找到他们的电话号码和地址。</p>
<p>如果要搜索的列表包含多个项目(比如十几个)，则二分查找将比线性搜索需要更少的比较，但它强制要求对列表进行排序。</p>
<p>在计算机科学中，二分查找或半间隔搜索算法在按键值排序的数组中，查找指定输入值(搜索”关键字”)的位置。</p>
<p>在每个步骤中，算法将搜索关键字值与数组中间元素的值进行比较。</p>
<p>如果匹配，则找到匹配元素，并返回其索引或位置。</p>
<p>否则，如果搜索关键字小于中间元素的键，则算法在中间元素左侧的子阵列上重复其操作，或者如果搜索关键字更大，则在右侧的子阵列上重复其操作。</p>
<p>如果要搜索的剩余阵列为空，则在阵列中找不到该键值，并返回特殊的”not found”指示。</p>
<p>二分查找将每次迭代检查的项目数减半，因此定位项目(或确定其不存在)需要对数时间。二分搜索是一种对半分，并渐进的搜索算法。</p>
<a class="header" href="#限制-1" id="限制-1"><h2>限制</h2></a>
<p>Rust 已在其标准库中提供了一个<a href="https://doc.rust-lang.org/std/primitive.slice.html#method.binary_search">二分查找 函数</a>.对于本练习，您不应使用此函数，而应使用其他基本工具.</p>
<a class="header" href="#提示-1" id="提示-1"><h2>提示</h2></a>
<p><a href="https://doc.rust-lang.org/book/ch04-03-slices.html">Slices</a>除了具有通过索引，正常访问元素(slice[索引])，还有很多有用的函数，像<a href="https://doc.rust-lang.org/std/primitive.slice.html#method.split_at">split_at</a><a href="https://doc.rust-lang.org/std/primitive.slice.html#method.get">给予 子区间</a>(slice[start..end]).</p>
<p>您可以通过索引，使用无聊的旧元素访问来解决此练习，但也许其他提供的函数可以使您的代码更清晰，更安全.</p>
<a class="header" href="#加分-4" id="加分-4"><h2>加分</h2></a>
<p>你是否通过了测试并且代码干净了?如果你愿意，你可以尝试一些其他的东西.</p>
<ul>
<li>目前，您的查找函数可能仅适用于数字切片，但 Rust 类型系统足够灵活，可以创建一个查找函数，该函数适用于包含可排序元素的所有切片.</li>
<li>此外，此查找函数不仅可以在切片上工作，还可以在 Vec 或数组上同时工作.</li>
</ul>
<p>要运行加分测试，请删除<code>#[ignore]</code>标记，并执行测试<code>generic</code>函数，像这样:</p>
<pre><code class="language-bash">$ cargo test --features generic
</code></pre>
<a class="header" href="#加分的提示" id="加分的提示"><h3>加分的提示</h3></a>
<ul>
<li>为了使您的函数与所有可排序的元素一起使用，请查看<a href="https://doc.rust-lang.org/std/cmp/trait.Ord.html">Ord Trait</a>.</li>
<li>要使您的函数直接在 Vec 和 Array 上运行，您可以使用<a href="https://doc.rust-lang.org/std/convert/trait.AsRef.html">AsRef Trait</a></li>
</ul>
<a class="header" href="#资源-39" id="资源-39"><h2>资源</h2></a>
<p>维基百科<a href="http://en.wikipedia.org/wiki/Binary_search_algorithm">http://en.wikipedia.org/wiki/Binary_search_algorithm</a></p>
<a class="header" href="#2-开始你的表演-50" id="2-开始你的表演-50"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn find(array: &amp;[i32], key: i32) -&gt; Option&lt;usize&gt; {
   unimplemented!(
       &quot;Using the binary search algorithm, find the element '{}' in the array '{:?}' and return its index.&quot;,
       key,
       array
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-50" id="3-测试代码查看-50"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn finds_a_value_in_an_array_with_one_element() {
   assert_eq!(find(&amp;[6], 6), Some(0));
}

#[test]
//#[ignore]
fn finds_first_value_in_an_array_with_two_element() {
   assert_eq!(find(&amp;[1, 2], 1), Some(0));
}

#[test]
//#[ignore]
fn finds_second_value_in_an_array_with_two_element() {
   assert_eq!(find(&amp;[1, 2], 2), Some(1));
}

#[test]
//#[ignore]
fn finds_a_value_in_the_middle_of_an_array() {
   assert_eq!(find(&amp;[1, 3, 4, 6, 8, 9, 11], 6), Some(3));
}

#[test]
//#[ignore]
fn finds_a_value_at_the_beginning_of_an_array() {
   assert_eq!(find(&amp;[1, 3, 4, 6, 8, 9, 11], 1), Some(0));
}

#[test]
//#[ignore]
fn finds_a_value_at_the_end_of_an_array() {
   assert_eq!(find(&amp;[1, 3, 4, 6, 8, 9, 11], 11), Some(6));
}

#[test]
//#[ignore]
fn finds_a_value_in_an_array_of_odd_length() {
   assert_eq!(
       find(&amp;[1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634], 144),
       Some(9)
   );
}

#[test]
//#[ignore]
fn finds_a_value_in_an_array_of_even_length() {
   assert_eq!(
       find(&amp;[1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377], 21),
       Some(5)
   );
}

#[test]
//#[ignore]
fn identifies_that_a_value_is_not_included_in_the_array() {
   assert_eq!(find(&amp;[1, 3, 4, 6, 8, 9, 11], 7), None);
}

#[test]
//#[ignore]
fn a_value_smaller_than_the_arrays_smallest_value_is_not_included() {
   assert_eq!(find(&amp;[1, 3, 4, 6, 8, 9, 11], 0), None);
}

#[test]
//#[ignore]
fn a_value_larger_than_the_arrays_largest_value_is_not_included() {
   assert_eq!(find(&amp;[1, 3, 4, 6, 8, 9, 11], 13), None);
}

#[test]
//#[ignore]
fn nothing_is_included_in_an_empty_array() {
   assert_eq!(find(&amp;[], 1), None);
}

#[test]
//#[ignore]
#[cfg(feature = &quot;generic&quot;)]
fn works_for_arrays() {
   assert_eq!(find([6], 6), Some(0));
}

#[test]
//#[ignore]
#[cfg(feature = &quot;generic&quot;)]
fn works_for_vec() {
   let vector = vec![6];
   assert_eq!(find(&amp;vector, 6), Some(0));
   assert_eq!(find(vector, 6), Some(0));
}

#[test]
//#[ignore]
#[cfg(feature = &quot;generic&quot;)]
fn works_for_str_elements() {
   assert_eq!(find([&quot;a&quot;], &quot;a&quot;), Some(0));
   assert_eq!(find([&quot;a&quot;, &quot;b&quot;], &quot;b&quot;), Some(1));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-50" id="4-答案-50"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::cmp::Ordering;

pub fn find&lt;C, T&gt;(elements: C, needle: T) -&gt; Option&lt;usize&gt;
where
   C: AsRef&lt;[T]&gt;,
   T: Ord,
{
   let mut base = 0usize;
   let mut slice: &amp;[T] = elements.as_ref();

   loop {
       let (head, tail) = slice.split_at(slice.len() &gt;&gt; 1);
       if let Some(middle_element) = tail.first() {
           match middle_element.cmp(&amp;needle) {
               Ordering::Less =&gt; {
                   base += head.len() + 1;
                   slice = &amp;tail[1..];
               }
               Ordering::Greater =&gt; slice = head,
               Ordering::Equal =&gt; {
                   return Some(base + head.len());
               }
           }
       } else {
           return None;
       }
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-50" id="填充相关-50"><h2>填充/相关</h2></a>
<a class="header" href="#robot-simulator" id="robot-simulator"><h1>Robot Simulator</h1></a>
<a class="header" href="#1-readme-51" id="1-readme-51"><h2>1. Readme</h2></a>
<a class="header" href="#机器人模拟器" id="机器人模拟器"><h1>机器人模拟器</h1></a>
<p>编写机器人模拟器。</p>
<p>机器人工厂的测试设施需要一个程序，来验证机器人的运动。</p>
<p>机器人有三种可能的运动:</p>
<ul>
<li>右转</li>
<li>左转</li>
<li>前进</li>
</ul>
<p>机器人被放置在一个假设的无限网格上，以一组{x，y}坐标，例如{3，8}面向特定方向(北、东、南或西)，能向北和东前进。</p>
<p>然后，机器人接收许多指令，测试设备验证机器人的新位置以及指向哪个方向。</p>
<ul>
<li>字母串”RAALAR”的意思是:
<ul>
<li>右转</li>
<li>前两次</li>
<li>向左拐</li>
<li>前一次</li>
<li>再次左转</li>
</ul>
</li>
<li>假设一个机器人从{ 7， 3 }向北开始，然后运行这个指令流，它应该就放在面向西方的{ 9, 4 }上。</li>
</ul>
<a class="header" href="#源" id="源"><h2>源</h2></a>
<p>灵感来自一个著名公司的面试问题.</p>
<a class="header" href="#2-开始你的表演-51" id="2-开始你的表演-51"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">// The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.

#[derive(PartialEq, Debug)]
pub enum Direction {
   North,
   East,
   South,
   West,
}

pub struct Robot;

impl Robot {
   pub fn new(x: i32, y: i32, d: Direction) -&gt; Self {
       unimplemented!(&quot;Create a robot at (x, y) ({}, {}) facing {:?}&quot;, x, y, d,)
   }

   pub fn turn_right(self) -&gt; Self {
       unimplemented!()
   }

   pub fn turn_left(self) -&gt; Self {
       unimplemented!()
   }

   pub fn advance(self) -&gt; Self {
       unimplemented!()
   }

   pub fn instructions(self, instructions: &amp;str) -&gt; Self {
       unimplemented!(
           &quot;Follow the given sequence of instructions: {}&quot;,
           instructions
       )
   }

   pub fn position(&amp;self) -&gt; (i32, i32) {
       unimplemented!()
   }

   pub fn direction(&amp;self) -&gt; &amp;Direction {
       unimplemented!()
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-51" id="3-测试代码查看-51"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn robots_are_created_with_position_and_direction() {
   let robot = Robot::new(0, 0, Direction::North);
   assert_eq!((0, 0), robot.position());
   assert_eq!(&amp;Direction::North, robot.direction());
}

#[test]
//#[ignore]
fn positions_can_be_negative() {
   let robot = Robot::new(-1, -1, Direction::South);
   assert_eq!((-1, -1), robot.position());
   assert_eq!(&amp;Direction::South, robot.direction());
}

#[test]
//#[ignore]
fn turning_right_does_not_change_position() {
   let robot = Robot::new(0, 0, Direction::North).turn_right();
   assert_eq!((0, 0), robot.position());
}

#[test]
//#[ignore]
fn turning_right_from_north_points_the_robot_east() {
   let robot = Robot::new(0, 0, Direction::North).turn_right();
   assert_eq!(&amp;Direction::East, robot.direction());
}

#[test]
//#[ignore]
fn turning_right_from_east_points_the_robot_south() {
   let robot = Robot::new(0, 0, Direction::East).turn_right();
   assert_eq!(&amp;Direction::South, robot.direction());
}

#[test]
//#[ignore]
fn turning_right_from_south_points_the_robot_west() {
   let robot = Robot::new(0, 0, Direction::South).turn_right();
   assert_eq!(&amp;Direction::West, robot.direction());
}

#[test]
//#[ignore]
fn turning_right_from_west_points_the_robot_north() {
   let robot = Robot::new(0, 0, Direction::West).turn_right();
   assert_eq!(&amp;Direction::North, robot.direction());
}

#[test]
//#[ignore]
fn turning_left_does_not_change_position() {
   let robot = Robot::new(0, 0, Direction::North).turn_left();
   assert_eq!((0, 0), robot.position());
}

#[test]
//#[ignore]
fn turning_left_from_north_points_the_robot_west() {
   let robot = Robot::new(0, 0, Direction::North).turn_left();
   assert_eq!(&amp;Direction::West, robot.direction());
}

#[test]
//#[ignore]
fn turning_left_from_west_points_the_robot_south() {
   let robot = Robot::new(0, 0, Direction::West).turn_left();
   assert_eq!(&amp;Direction::South, robot.direction());
}

#[test]
//#[ignore]
fn turning_left_from_south_points_the_robot_east() {
   let robot = Robot::new(0, 0, Direction::South).turn_left();
   assert_eq!(&amp;Direction::East, robot.direction());
}

#[test]
//#[ignore]
fn turning_left_from_east_points_the_robot_north() {
   let robot = Robot::new(0, 0, Direction::East).turn_left();
   assert_eq!(&amp;Direction::North, robot.direction());
}

#[test]
//#[ignore]
fn advance_does_not_change_the_direction() {
   let robot = Robot::new(0, 0, Direction::North).advance();
   assert_eq!(&amp;Direction::North, robot.direction());
}

#[test]
//#[ignore]
fn advance_increases_the_y_coordinate_by_one_when_facing_north() {
   let robot = Robot::new(0, 0, Direction::North).advance();
   assert_eq!((0, 1), robot.position());
}

#[test]
//#[ignore]
fn advance_decreases_the_y_coordinate_by_one_when_facing_south() {
   let robot = Robot::new(0, 0, Direction::South).advance();
   assert_eq!((0, -1), robot.position());
}

#[test]
//#[ignore]
fn advance_increases_the_x_coordinate_by_one_when_facing_east() {
   let robot = Robot::new(0, 0, Direction::East).advance();
   assert_eq!((1, 0), robot.position());
}

#[test]
//#[ignore]
fn advance_decreases_the_x_coordinate_by_one_when_facing_west() {
   let robot = Robot::new(0, 0, Direction::West).advance();
   assert_eq!((-1, 0), robot.position());
}

#[test]
//#[ignore]
fn follow_instructions_to_move_west_and_north() {
   let robot = Robot::new(0, 0, Direction::North).instructions(&quot;LAAARALA&quot;);
   assert_eq!((-4, 1), robot.position());
   assert_eq!(&amp;Direction::West, robot.direction());
}

#[test]
//#[ignore]
fn follow_instructions_to_move_west_and_south() {
   let robot = Robot::new(2, -7, Direction::East).instructions(&quot;RRAAAAALA&quot;);
   assert_eq!((-3, -8), robot.position());
   assert_eq!(&amp;Direction::South, robot.direction());
}

#[test]
//#[ignore]
fn follow_instructions_to_move_east_and_north() {
   let robot = Robot::new(8, 4, Direction::South).instructions(&quot;LAAARRRALLLL&quot;);
   assert_eq!((11, 5), robot.position());
   assert_eq!(&amp;Direction::North, robot.direction());
}

#}</code></pre></pre>
<a class="header" href="#4-答案-51" id="4-答案-51"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum Direction {
   North,
   East,
   South,
   West,
}

impl Direction {
   pub fn previous_clockwise(&amp;self) -&gt; Self {
       match *self {
           Direction::North =&gt; Direction::West,
           Direction::East =&gt; Direction::North,
           Direction::South =&gt; Direction::East,
           Direction::West =&gt; Direction::South,
       }
   }

   pub fn next_clockwise(&amp;self) -&gt; Self {
       match *self {
           Direction::North =&gt; Direction::East,
           Direction::East =&gt; Direction::South,
           Direction::South =&gt; Direction::West,
           Direction::West =&gt; Direction::North,
       }
   }
}

#[derive(Clone, Copy)]
struct Position {
   x: i32,
   y: i32,
}

impl Position {
   fn new(x: i32, y: i32) -&gt; Self {
       Position { x: x, y: y }
   }

   fn advance(&amp;self, direction: &amp;Direction) -&gt; Self {
       match *direction {
           Direction::North =&gt; Self::new(self.x, self.y + 1),
           Direction::South =&gt; Self::new(self.x, self.y - 1),
           Direction::East =&gt; Self::new(self.x + 1, self.y),
           Direction::West =&gt; Self::new(self.x - 1, self.y),
       }
   }
}

#[derive(Clone)]
pub struct Robot {
   position: Position,
   direction: Direction,
}

impl Robot {
   pub fn new(x: i32, y: i32, d: Direction) -&gt; Self {
       Robot::build(Position::new(x, y), d)
   }

   fn build(position: Position, direction: Direction) -&gt; Self {
       Robot {
           position: position,
           direction: direction,
       }
   }

   pub fn turn_right(&amp;self) -&gt; Self {
       Self::build(self.position, self.direction.next_clockwise())
   }

   pub fn turn_left(&amp;self) -&gt; Self {
       Self::build(self.position, self.direction.previous_clockwise())
   }

   pub fn advance(&amp;self) -&gt; Self {
       Self::build(self.position.advance(&amp;self.direction), self.direction)
   }

   pub fn instructions(&amp;self, instructions: &amp;str) -&gt; Self {
       instructions
           .chars()
           .fold(self.clone(), |robot, instruction| {
               robot.execute(instruction)
           })
   }

   pub fn position(&amp;self) -&gt; (i32, i32) {
       (self.position.x, self.position.y)
   }

   pub fn direction(&amp;self) -&gt; &amp;Direction {
       &amp;self.direction
   }

   fn execute(self, command: char) -&gt; Self {
       match command {
           'R' =&gt; self.turn_right(),
           'L' =&gt; self.turn_left(),
           'A' =&gt; self.advance(),
           _ =&gt; self,
       }
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-51" id="填充相关-51"><h2>填充/相关</h2></a>
<a class="header" href="#bracket-push" id="bracket-push"><h1>Bracket Push</h1></a>
<a class="header" href="#1-readme-52" id="1-readme-52"><h2>1. Readme</h2></a>
<a class="header" href="#括号配套" id="括号配套"><h1>括号配套</h1></a>
<p>给定包含括号<code>[]</code>大括号<code>{}</code>括号<code>()</code>或它们的任何组合的字符串，验证任何和所有对，都被正确地匹配和嵌套。</p>
<a class="header" href="#资源-40" id="资源-40"><h2>资源</h2></a>
<p>Ginna Baker</p>
<a class="header" href="#2-开始你的表演-52" id="2-开始你的表演-52"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn brackets_are_balanced(string: &amp;str) -&gt; bool {
   unimplemented!(&quot;Check if the string \&quot;{}\&quot; contains balanced brackets&quot;, string);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-52" id="3-测试代码查看-52"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn paired_square_brackets() {
   assert!(brackets_are_balanced(&quot;[]&quot;));
}

#[test]
//#[ignore]
fn empty_string() {
   assert!(brackets_are_balanced(&quot;&quot;));
}

#[test]
//#[ignore]
fn unpaired_brackets() {
   assert!(!brackets_are_balanced(&quot;[[&quot;));
}

#[test]
//#[ignore]
fn wrong_ordered_brackets() {
   assert!(!brackets_are_balanced(&quot;}{&quot;));
}

#[test]
//#[ignore]
fn wrong_closing_bracket() {
   assert!(!brackets_are_balanced(&quot;{]&quot;));
}

#[test]
//#[ignore]
fn paired_with_whitespace() {
   assert!(brackets_are_balanced(&quot;{ }&quot;));
}

#[test]
//#[ignore]
fn simple_nested_brackets() {
   assert!(brackets_are_balanced(&quot;{[]}&quot;));
}

#[test]
//#[ignore]
fn several_paired_brackets() {
   assert!(brackets_are_balanced(&quot;{}[]&quot;));
}

#[test]
//#[ignore]
fn paired_and_nested_brackets() {
   assert!(brackets_are_balanced(&quot;([{}({}[])])&quot;));
}

#[test]
//#[ignore]
fn unopened_closing_brackets() {
   assert!(!brackets_are_balanced(&quot;{[)][]}&quot;));
}

#[test]
//#[ignore]
fn unpaired_and_nested_brackets() {
   assert!(!brackets_are_balanced(&quot;([{])&quot;));
}

#[test]
//#[ignore]
fn paired_and_wrong_nested_brackets() {
   assert!(!brackets_are_balanced(&quot;[({]})&quot;));
}

#[test]
//#[ignore]
fn math_expression() {
   assert!(brackets_are_balanced(&quot;(((185 + 223.85) * 15) - 543)/2&quot;));
}

#[test]
//#[ignore]
fn complex_latex_expression() {
   let input = &quot;\\left(\\begin{array}{cc} \\frac{1}{3} &amp; x\\\\ \\mathrm{e}^{x} &amp;... x^2 \
                \\end{array}\\right)&quot;;
   assert!(brackets_are_balanced(input));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-52" id="4-答案-52"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;

pub fn brackets_are_balanced(string: &amp;str) -&gt; bool {
   Brackets::from(string).are_balanced()
}

struct Brackets {
   raw_brackets: Vec&lt;char&gt;,
   pairs: MatchingBrackets,
}

impl&lt;'a&gt; From&lt;&amp;'a str&gt; for Brackets {
   fn from(i: &amp;str) -&gt; Self {
       Brackets::new(String::from(i), None)
   }
}

impl Brackets {
   fn new(s: String, pairs: Option&lt;Vec&lt;(char, char)&gt;&gt;) -&gt; Self {
       let p = match pairs {
           Some(x) =&gt; MatchingBrackets::from(x),
           None =&gt; MatchingBrackets::from(vec![('[', ']'), ('{', '}'), ('(', ')')]),
       };

       Brackets {
           raw_brackets: s.chars().filter(|c| p.contains(&amp;c)).collect::&lt;Vec&lt;char&gt;&gt;(),
           pairs: p,
       }
   }

   fn are_balanced(&amp;self) -&gt; bool {
       let mut unclosed: Vec&lt;char&gt; = Vec::new();

       for &amp;bracket in self.raw_brackets.iter() {
           if let Some(last_unclosed) = unclosed.pop() {
               unclosed.extend(self.pairs.unmatched(last_unclosed, bracket));
           } else {
               unclosed.push(bracket);
           }
       }

       unclosed.is_empty()
   }
}

struct MatchingBrackets {
   collection: HashMap&lt;char, char&gt;,
}

impl From&lt;Vec&lt;(char, char)&gt;&gt; for MatchingBrackets {
   fn from(v: Vec&lt;(char, char)&gt;) -&gt; Self {
       MatchingBrackets {
           collection: v.into_iter().collect::&lt;HashMap&lt;char, char&gt;&gt;(),
       }
   }
}

impl MatchingBrackets {
   fn contains(&amp;self, other: &amp;char) -&gt; bool {
       let known = self.collection
           .keys()
           .chain(self.collection.values())
           .collect::&lt;Vec&lt;_&gt;&gt;();
       known.contains(&amp;other)
   }

   fn closer_for(&amp;self, k: &amp;char) -&gt; Option&lt;&amp;char&gt; {
       self.collection.get(k)
   }

   fn closed_by(&amp;self, l: char, r: char) -&gt; bool {
       match self.closer_for(&amp;l) {
           Some(&amp;x) =&gt; r == x,
           None =&gt; false,
       }
   }

   fn unmatched(&amp;self, open: char, potential_close: char) -&gt; Vec&lt;char&gt; {
       let mut ret: Vec&lt;char&gt; = Vec::new();

       if !self.closed_by(open, potential_close) {
           ret.push(open);
           ret.push(potential_close);
       }

       ret
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-52" id="填充相关-52"><h2>填充/相关</h2></a>
<a class="header" href="#luhn-from" id="luhn-from"><h1>Luhn From</h1></a>
<a class="header" href="#1-readme-53" id="1-readme-53"><h2>1. Readme</h2></a>
<a class="header" href="#来自-luhn" id="来自-luhn"><h1>来自 Luhn</h1></a>
<a class="header" href="#luhn使用-from-trait" id="luhn使用-from-trait"><h1>Luhn:使用 From Trait</h1></a>
<p>在做这个练习之前，你应该做原始的 LuHn 练习。如果您还没有完成 Luhn，您可以通过运行命令来获得它:</p>
<pre><code class="language-shell">exercism download --exercise=luhn --track=rust
</code></pre>
<p>在原始的 LuHn 练习中，您只验证字符串，但 Luhn 算法也可以应用于整数。</p>
<p>在本练习中，您将实现<a href="https://doc.rust-lang.org/std/convert/trait.From.html">From trait</a>，用来将字符串、strs 和无符号整数转换为执行验证的结构。</p>
<a class="header" href="#资源-41" id="资源-41"><h2>资源</h2></a>
<p>The Rust track maintainers，基于原始 Luhn 练习</p>
<a class="header" href="#2-开始你的表演-53" id="2-开始你的表演-53"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub struct Luhn;

impl Luhn {
   pub fn is_valid(&amp;self) -&gt; bool {
       unimplemented!(&quot;Determine if the current Luhn struct contains a valid credit card number.&quot;);
   }
}

/// Here is the example of how the From trait could be implemented
/// for the &amp;str type. Naturally, you can implement this trait
/// by hand for the every other type presented in the test suite,
/// but your solution will fail if a new type is presented.
/// Perhaps there exists a better solution for this problem?
impl&lt;'a&gt; From&lt;&amp;'a str&gt; for Luhn {
   fn from(input: &amp;'a str) -&gt; Self {
       unimplemented!(&quot;From the given input '{}' create a new Luhn struct.&quot;, input);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-53" id="3-测试代码查看-53"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn you_can_validate_from_a_str() {
   let valid = Luhn::from(&quot;046 454 286&quot;);
   let invalid = Luhn::from(&quot;046 454 287&quot;);
   assert!(valid.is_valid());
   assert!(!invalid.is_valid());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_string() {
   let valid = Luhn::from(String::from(&quot;046 454 286&quot;));
   let invalid = Luhn::from(String::from(&quot;046 454 287&quot;));
   assert!(valid.is_valid());
   assert!(!invalid.is_valid());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_u8() {
   let valid = Luhn::from(240u8);
   let invalid = Luhn::from(241u8);
   assert!(valid.is_valid());
   assert!(!invalid.is_valid());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_u16() {
   let valid = Luhn::from(64_436u16);
   let invalid = Luhn::from(64_437u16);
   assert!(valid.is_valid());
   assert!(!invalid.is_valid());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_u32() {
   let valid = Luhn::from(46_454_286u32);
   let invalid = Luhn::from(46_454_287u32);
   assert!(valid.is_valid());
   assert!(!invalid.is_valid());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_u64() {
   let valid = Luhn::from(8273_1232_7352_0562u64);
   let invalid = Luhn::from(8273_1232_7352_0569u64);
   assert!(valid.is_valid());
   assert!(!invalid.is_valid());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_usize() {
   let valid = Luhn::from(8273_1232_7352_0562usize);
   let invalid = Luhn::from(8273_1232_7352_0569usize);
   assert!(valid.is_valid());
   assert!(!invalid.is_valid());
}

#[test]
//#[ignore]
fn single_digit_string_is_invalid() {
   assert!(!Luhn::from(&quot;1&quot;).is_valid());
}

#[test]
//#[ignore]
fn single_zero_string_is_invalid() {
   assert!(!Luhn::from(&quot;0&quot;).is_valid());
}

#[test]
//#[ignore]
fn valid_canadian_sin_is_valid() {
   assert!(Luhn::from(&quot;046 454 286&quot;).is_valid());
}

#[test]
//#[ignore]
fn invalid_canadian_sin_is_invalid() {
   assert!(!Luhn::from(&quot;046 454 287&quot;).is_valid());
}

#[test]
//#[ignore]
fn invalid_credit_card_is_invalid() {
   assert!(!Luhn::from(&quot;8273 1232 7352 0569&quot;).is_valid());
}

#[test]
//#[ignore]
fn strings_that_contain_non_digits_are_invalid() {
   assert!(!Luhn::from(&quot;046a 454 286&quot;).is_valid());
}

#}</code></pre></pre>
<a class="header" href="#4-答案-53" id="4-答案-53"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub struct Luhn {
   digits: Vec&lt;char&gt;,
}

impl Luhn {
   pub fn is_valid(&amp;self) -&gt; bool {
       if self.digits.iter().any(|c| c.is_alphabetic()) || self.digits.iter().count() == 1 {
           return false;
       }

       self.digits
           .iter()
           .filter_map(|c| c.to_digit(10))
           .rev()
           .enumerate()
           .map(|(index, digit)| if index % 2 == 0 { digit } else { digit * 2 })
           .map(|digit| if digit &gt; 9 { digit - 9 } else { digit })
           .sum::&lt;u32&gt;() % 10 == 0
   }
}

impl From&lt;String&gt; for Luhn {
   fn from(s: String) -&gt; Self {
       Luhn {
           digits: s.chars().collect(),
       }
   }
}

impl&lt;'a&gt; From&lt;&amp;'a str&gt; for Luhn {
   fn from(s: &amp;'a str) -&gt; Self {
       Luhn::from(String::from(s))
   }
}

impl From&lt;u8&gt; for Luhn {
   fn from(s: u8) -&gt; Self {
       Luhn::from(s.to_string())
   }
}

impl From&lt;u16&gt; for Luhn {
   fn from(s: u16) -&gt; Self {
       Luhn::from(s.to_string())
   }
}

impl From&lt;u32&gt; for Luhn {
   fn from(s: u32) -&gt; Self {
       Luhn::from(s.to_string())
   }
}

impl From&lt;u64&gt; for Luhn {
   fn from(s: u64) -&gt; Self {
       Luhn::from(s.to_string())
   }
}

impl From&lt;usize&gt; for Luhn {
   fn from(s: usize) -&gt; Self {
       Luhn::from(s.to_string())
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-53" id="填充相关-53"><h2>填充/相关</h2></a>
<a class="header" href="#queen-attack" id="queen-attack"><h1>Queen Attack</h1></a>
<a class="header" href="#1-readme-54" id="1-readme-54"><h2>1. Readme</h2></a>
<a class="header" href="#女王攻击" id="女王攻击"><h1>女王攻击</h1></a>
<p>给定棋盘上的两个皇后的位置，指示在各自位置的它们，是否能互相攻击。</p>
<p>在象棋游戏中，女王可以攻击同一行、列或对角线上的棋子。</p>
<p>棋盘可以用 8 乘 8 的数组来表示。</p>
<p>所以如果你告诉白皇后在(2， 3)和黑皇后在(5， 6)，那么设定像这样:</p>
<pre><code class="language-text">_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ W _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ B _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
</code></pre>
<p>你也可以回答女王是否可以互相攻击。而在这种情况下，答案是肯定的，他们可以，因为这两个部分共用一个对角线。</p>
<a class="header" href="#资源-42" id="资源-42"><h2>资源</h2></a>
<p>J Dalbey 的程序设计实践问题<a href="http://users.csc.calpoly.edu/%7Ejdalbey/103/Projects/ProgrammingPractice.html">http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html</a></p>
<a class="header" href="#2-开始你的表演-54" id="2-开始你的表演-54"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">#[derive(Debug)]
pub struct ChessPosition;

#[derive(Debug)]
pub struct Queen;

impl ChessPosition {
   pub fn new(rank: i32, file: i32) -&gt; Option&lt;Self&gt; {
       unimplemented!(
           &quot;Construct a ChessPosition struct, given the following rank, file: ({}, {}). If the position is invalid return None.&quot;,
           rank,
           file
       );
   }
}

impl Queen {
   pub fn new(position: ChessPosition) -&gt; Self {
       unimplemented!(
           &quot;Given the chess position {:?}, construct a Queen struct.&quot;,
           position
       );
   }

   pub fn can_attack(&amp;self, other: &amp;Queen) -&gt; bool {
       unimplemented!(
           &quot;Determine if this Queen can attack the other Queen {:?}&quot;,
           other
       );
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-54" id="3-测试代码查看-54"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn chess_position_on_the_board_is_some() {
   assert!(ChessPosition::new(2, 4).is_some());
}

#[test]
//#[ignore]
fn chess_position_off_the_board_is_none() {
   assert!(ChessPosition::new(-1, 2).is_none());

   assert!(ChessPosition::new(8, 2).is_none());

   assert!(ChessPosition::new(5, -1).is_none());

   assert!(ChessPosition::new(5, 8).is_none());
}

#[test]
//#[ignore]
fn queen_is_created_with_a_valid_position() {
   Queen::new(ChessPosition::new(2, 4).unwrap());
}

#[test]
//#[ignore]
fn queens_that_can_not_attack() {
   let white_queen = Queen::new(ChessPosition::new(2, 4).unwrap());
   let black_queen = Queen::new(ChessPosition::new(6, 6).unwrap());

   assert!(!white_queen.can_attack(&amp;black_queen));
}

#[test]
//#[ignore]
fn queens_on_the_same_rank_can_attack() {
   let white_queen = Queen::new(ChessPosition::new(2, 4).unwrap());
   let black_queen = Queen::new(ChessPosition::new(2, 6).unwrap());

   assert!(white_queen.can_attack(&amp;black_queen));
}

#[test]
//#[ignore]
fn queens_on_the_same_file_can_attack() {
   let white_queen = Queen::new(ChessPosition::new(4, 5).unwrap());
   let black_queen = Queen::new(ChessPosition::new(3, 5).unwrap());

   assert!(white_queen.can_attack(&amp;black_queen));
}

#[test]
//#[ignore]
fn queens_on_the_same_diagonal_can_attack_one() {
   let white_queen = Queen::new(ChessPosition::new(2, 2).unwrap());
   let black_queen = Queen::new(ChessPosition::new(0, 4).unwrap());

   assert!(white_queen.can_attack(&amp;black_queen));
}

#[test]
//#[ignore]
fn queens_on_the_same_diagonal_can_attack_two() {
   let white_queen = Queen::new(ChessPosition::new(2, 2).unwrap());
   let black_queen = Queen::new(ChessPosition::new(3, 1).unwrap());

   assert!(white_queen.can_attack(&amp;black_queen));
}

#[test]
//#[ignore]
fn queens_on_the_same_diagonal_can_attack_three() {
   let white_queen = Queen::new(ChessPosition::new(2, 2).unwrap());
   let black_queen = Queen::new(ChessPosition::new(1, 1).unwrap());

   assert!(white_queen.can_attack(&amp;black_queen));
}

#[test]
//#[ignore]
fn queens_on_the_same_diagonal_can_attack_four() {
   let white_queen = Queen::new(ChessPosition::new(2, 2).unwrap());
   let black_queen = Queen::new(ChessPosition::new(5, 5).unwrap());

   assert!(white_queen.can_attack(&amp;black_queen));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-54" id="4-答案-54"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[derive(Debug)]
pub struct Queen {
   position: ChessPosition,
}

pub trait ChessPiece {
   fn position(&amp;self) -&gt; &amp;ChessPosition;
   fn can_attack&lt;T: ChessPiece&gt;(&amp;self, other: &amp;T) -&gt; bool;
}

impl ChessPiece for Queen {
   fn position(&amp;self) -&gt; &amp;ChessPosition {
       &amp;self.position
   }

   fn can_attack&lt;T: ChessPiece&gt;(&amp;self, piece: &amp;T) -&gt; bool {
       self.position.horizontal_from(&amp;piece.position())
           || self.position.vertical_from(&amp;piece.position())
           || self.position.diagonal_from(&amp;piece.position())
   }
}

impl Queen {
   pub fn new(position: ChessPosition) -&gt; Queen {
       Queen { position: position }
   }
}

#[derive(Debug)]
pub struct ChessPosition {
   pub rank: i8,
   pub file: i8,
}

impl ChessPosition {
   pub fn new(rank: i8, file: i8) -&gt; Option&lt;Self&gt; {
       let position = ChessPosition {
           rank: rank,
           file: file,
       };

       if position.is_valid() {
           Some(position)
       } else {
           None
       }
   }

   fn is_valid(&amp;self) -&gt; bool {
       self.rank &gt;= 0 &amp;&amp; self.rank &lt;= 7 &amp;&amp; self.file &gt;= 0 &amp;&amp; self.file &lt;= 7
   }

   fn horizontal_from(&amp;self, other: &amp;ChessPosition) -&gt; bool {
       self.rank == other.rank
   }

   fn vertical_from(&amp;self, other: &amp;ChessPosition) -&gt; bool {
       self.file == other.file
   }

   fn diagonal_from(&amp;self, other: &amp;ChessPosition) -&gt; bool {
       self.sum() == other.sum() || self.difference() == other.difference()
   }

   fn sum(&amp;self) -&gt; i8 {
       self.rank + self.file
   }

   fn difference(&amp;self) -&gt; i8 {
       self.rank - self.file
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-54" id="填充相关-54"><h2>填充/相关</h2></a>
<a class="header" href="#bowling" id="bowling"><h1>Bowling</h1></a>
<a class="header" href="#1-readme-55" id="1-readme-55"><h2>1. Readme</h2></a>
<a class="header" href="#保龄球" id="保龄球"><h1>保龄球</h1></a>
<p>打保龄球比赛。</p>
<p>保龄球是一种游戏，玩家掷出一个沉重的球来击倒排列成三角形的罐子。编写代码以跟踪保龄球比赛的得分。</p>
<a class="header" href="#保龄球得分" id="保龄球得分"><h2>保龄球得分</h2></a>
<p>游戏由 10 轮组成。一轮由一个或两个球投掷组成，其中 10 个罐子处于该轮初始化状态。一个回合有三种情况。</p>
<ul>
<li>
<p>开放(open)轮是轮的记录小于 10 的分数。在这种情况下，该轮的分数是被击倒数。</p>
</li>
<li>
<p>备用(spare)的是所有十个罐子被第二次投掷击倒。备用的总分是 10 加上，下一次投掷击倒的罐子数量。</p>
</li>
<li>
<p>全倒(strike)是所有十个罐子被第一次击倒。全倒的总分是 10 加上，在接下来的两次投掷击倒的罐子数量。如果进行第二次击球又触发 strike，则再扔球之前不确定第一次击球的值。</p>
</li>
</ul>
<p>这是一个三轮的例子:</p>
<table><thead><tr><th align="center">  第 1 轮  </th><th align="center">  第 2 轮   </th><th align="center">  第 3 轮  </th></tr></thead><tbody>
<tr><td align="center"> X(strike) </td><td align="center"> 5 /(spare) </td><td align="center"> 9 0(open) </td></tr>
</tbody></table>
<p>第 1 轮是(10 + 5 + 5)= 20</p>
<p>第 2 轮是(5 + 5 + 9)= 19</p>
<p>轮 3 是(9 + 0)= 9</p>
<p>这意味着当前的运行总数为 48.</p>
<p>游戏中的第十轮是一个特例。如果有人投掷全倒或备用，那么他们会得到一个补球。补球会计入第 10 轮的总和。在补球上获得一次全倒或备用不会给球员带来更多的补球。第 10 轮的总分是被击倒的罐子总数。</p>
<p>对于 X1 /(全倒和备用)的第十轮，总分为 20。</p>
<p>对于 XXX (三次全倒)的第十轮，总分为 30。</p>
<a class="header" href="#要求" id="要求"><h2>要求</h2></a>
<p>编写代码以跟踪保龄球比赛的得分。它应该支持两个操作:</p>
<ul>
<li><code>roll(pins : int)</code>每次玩家滚球时都会调用。这个参数是被击倒的罐子数量.</li>
<li><code>score() : int</code>仅在游戏结束时才会被调用。它返回该游戏的总分。</li>
</ul>
<a class="header" href="#资源-43" id="资源-43"><h2>资源</h2></a>
<p>保龄球比赛， Kata 的 UncleBob<a href="http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata">http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata</a></p>
<a class="header" href="#2-开始你的表演-55" id="2-开始你的表演-55"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">#[derive(Debug, PartialEq)]
pub enum Error {
   NotEnoughPinsLeft,
   GameComplete,
}

pub struct BowlingGame {}

impl BowlingGame {
   pub fn new() -&gt; Self {
       unimplemented!();
   }

   pub fn roll(&amp;mut self, pins: u16) -&gt; Result&lt;(), Error&gt; {
       unimplemented!(&quot;Record that {} pins have been scored&quot;, pins);
   }

   pub fn score(&amp;self) -&gt; Option&lt;u16&gt; {
       unimplemented!(&quot;Return the score if the game is complete, or None if not.&quot;);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-55" id="3-测试代码查看-55"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn roll_returns_a_result() {
   let mut game = BowlingGame::new();
   assert!(game.roll(0).is_ok());
}

#[test]
//#[ignore]
fn you_can_not_roll_more_than_ten_pins_in_a_single_roll() {
   let mut game = BowlingGame::new();

   assert_eq!(game.roll(11), Err(Error::NotEnoughPinsLeft));;
}

#[test]
//#[ignore]
fn a_game_score_is_some_if_ten_frames_have_been_rolled() {
   let mut game = BowlingGame::new();

   for _ in 0..10 {
       let _ = game.roll(0);
       let _ = game.roll(0);
   }

   assert!(game.score().is_some());
}

#[test]
//#[ignore]
fn you_can_not_score_a_game_with_no_rolls() {
   let game = BowlingGame::new();

   assert_eq!(game.score(), None);
}

#[test]
//#[ignore]
fn a_game_score_is_none_if_fewer_than_ten_frames_have_been_rolled() {
   let mut game = BowlingGame::new();

   for _ in 0..9 {
       let _ = game.roll(0);
       let _ = game.roll(0);
   }

   assert_eq!(game.score(), None);
}

#[test]
//#[ignore]
fn a_roll_is_err_if_the_game_is_done() {
   let mut game = BowlingGame::new();

   for _ in 0..10 {
       let _ = game.roll(0);
       let _ = game.roll(0);
   }

   assert_eq!(game.roll(0), Err(Error::GameComplete));;
}

#[test]
//#[ignore]
fn twenty_zero_pin_rolls_scores_zero() {
   let mut game = BowlingGame::new();

   for _ in 0..20 {
       let _ = game.roll(0);
   }

   assert_eq!(game.score(), Some(0));
}

#[test]
//#[ignore]
fn ten_frames_without_a_strike_or_spare() {
   let mut game = BowlingGame::new();

   for _ in 0..10 {
       let _ = game.roll(3);
       let _ = game.roll(6);
   }

   assert_eq!(game.score(), Some(90));
}

#[test]
//#[ignore]
fn spare_in_the_first_frame_followed_by_zeros() {
   let mut game = BowlingGame::new();

   let _ = game.roll(6);
   let _ = game.roll(4);

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   assert_eq!(game.score(), Some(10));
}

#[test]
//#[ignore]
fn points_scored_in_the_roll_after_a_spare_are_counted_twice_as_a_bonus() {
   let mut game = BowlingGame::new();

   let _ = game.roll(6);
   let _ = game.roll(4);
   let _ = game.roll(3);

   for _ in 0..17 {
       let _ = game.roll(0);
   }

   assert_eq!(game.score(), Some(16));
}

#[test]
//#[ignore]
fn consecutive_spares_each_get_a_one_roll_bonus() {
   let mut game = BowlingGame::new();

   let _ = game.roll(5);
   let _ = game.roll(5);
   let _ = game.roll(3);
   let _ = game.roll(7);
   let _ = game.roll(4);

   for _ in 0..15 {
       let _ = game.roll(0);
   }

   assert_eq!(game.score(), Some(31));
}

#[test]
//#[ignore]
fn if_the_last_frame_is_a_spare_you_get_one_extra_roll_that_is_scored_once() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(5);
   let _ = game.roll(5);
   let _ = game.roll(7);

   assert_eq!(game.score(), Some(17));
}

#[test]
//#[ignore]
fn a_strike_earns_ten_points_in_a_frame_with_a_single_roll() {
   let mut game = BowlingGame::new();

   let _ = game.roll(10);

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   assert_eq!(game.score(), Some(10));
}

#[test]
//#[ignore]
fn points_scored_in_the_two_rolls_after_a_strike_are_counted_twice_as_a_bonus() {
   let mut game = BowlingGame::new();

   let _ = game.roll(10);
   let _ = game.roll(5);
   let _ = game.roll(3);

   for _ in 0..16 {
       let _ = game.roll(0);
   }

   assert_eq!(game.score(), Some(26));
}

#[test]
//#[ignore]
fn consecutive_strikes_each_get_the_two_roll_bonus() {
   let mut game = BowlingGame::new();

   let _ = game.roll(10);
   let _ = game.roll(10);
   let _ = game.roll(10);
   let _ = game.roll(5);
   let _ = game.roll(3);

   for _ in 0..12 {
       let _ = game.roll(0);
   }

   assert_eq!(game.score(), Some(81));
}

#[test]
//#[ignore]
fn a_strike_in_the_last_frame_earns_a_two_roll_bonus_that_is_counted_once() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(10);
   let _ = game.roll(7);
   let _ = game.roll(1);

   assert_eq!(game.score(), Some(18));
}

#[test]
//#[ignore]
fn a_spare_with_the_two_roll_bonus_does_not_get_a_bonus_roll() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(10);
   let _ = game.roll(7);
   let _ = game.roll(3);

   assert_eq!(game.score(), Some(20));
}

#[test]
//#[ignore]
fn strikes_with_the_two_roll_bonus_do_not_get_a_bonus_roll() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(10);
   let _ = game.roll(10);
   let _ = game.roll(10);

   assert_eq!(game.score(), Some(30));
}

#[test]
//#[ignore]
fn a_strike_with_the_one_roll_bonus_after_a_spare_in_the_last_frame_does_not_get_a_bonus() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(7);
   let _ = game.roll(3);
   let _ = game.roll(10);

   assert_eq!(game.score(), Some(20));
}

#[test]
//#[ignore]
fn all_strikes_is_a_perfect_score_of_300() {
   let mut game = BowlingGame::new();

   for _ in 0..12 {
       let _ = game.roll(10);
   }

   assert_eq!(game.score(), Some(300));
}

#[test]
//#[ignore]
fn you_can_not_roll_more_than_ten_pins_in_a_single_frame() {
   let mut game = BowlingGame::new();

   assert!(game.roll(5).is_ok());
   assert_eq!(game.roll(6), Err(Error::NotEnoughPinsLeft));;
}

#[test]
//#[ignore]
fn first_bonus_ball_after_a_final_strike_can_not_score_an_invalid_number_of_pins() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(10);

   assert_eq!(game.roll(11), Err(Error::NotEnoughPinsLeft));;
}

#[test]
//#[ignore]
fn the_two_balls_after_a_final_strike_can_not_score_an_invalid_number_of_pins() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(10);

   assert!(game.roll(5).is_ok());
   assert_eq!(game.roll(6), Err(Error::NotEnoughPinsLeft));;
}

#[test]
//#[ignore]
fn the_two_balls_after_a_final_strike_can_be_a_strike_and_non_strike() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(10);

   assert!(game.roll(10).is_ok());
   assert!(game.roll(6).is_ok());
}

#[test]
//#[ignore]
fn the_two_balls_after_a_final_strike_can_not_be_a_non_strike_followed_by_a_strike() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(10);

   assert!(game.roll(6).is_ok());
   assert_eq!(game.roll(10), Err(Error::NotEnoughPinsLeft));;
}

#[test]
//#[ignore]
fn second_bonus_ball_after_a_final_strike_can_not_score_an_invalid_number_of_pins_even_if_first_is_strike(
) {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(10);

   assert!(game.roll(10).is_ok());
   assert_eq!(game.roll(11), Err(Error::NotEnoughPinsLeft));;
}

#[test]
//#[ignore]
fn if_the_last_frame_is_a_strike_you_can_not_score_before_the_extra_rolls_are_taken() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(10);

   assert_eq!(game.score(), None);

   let _ = game.roll(10);

   assert_eq!(game.score(), None);

   let _ = game.roll(10);

   assert!(game.score().is_some());
}

#[test]
//#[ignore]
fn if_the_last_frame_is_a_spare_you_can_not_create_a_score_before_extra_roll_is_taken() {
   let mut game = BowlingGame::new();

   for _ in 0..18 {
       let _ = game.roll(0);
   }

   let _ = game.roll(5);
   let _ = game.roll(5);

   assert_eq!(game.score(), None);

   let _ = game.roll(10);

   assert!(game.score().is_some());
}

#}</code></pre></pre>
<a class="header" href="#4-答案-55" id="4-答案-55"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[derive(Debug, PartialEq)]
pub enum Error {
   NotEnoughPinsLeft,
   GameComplete,
}

pub struct BowlingGame {
   frames: Vec&lt;Frame&gt;,
}

struct Frame {
   rolls: Vec&lt;u16&gt;,
   bonus: Vec&lt;u16&gt;,
}

impl Frame {
   fn score(&amp;self) -&gt; u16 {
       self.roll_score() + self.bonus_score()
   }

   fn roll_score(&amp;self) -&gt; u16 {
       self.rolls.iter().sum()
   }

   fn bonus_score(&amp;self) -&gt; u16 {
       self.bonus.iter().sum()
   }

   fn is_valid(&amp;self) -&gt; bool {
       self.rolls_valid() &amp;&amp; self.bonus_valid()
   }

   fn rolls_valid(&amp;self) -&gt; bool {
       self.roll_score() &lt;= 10
   }

   fn bonus_valid(&amp;self) -&gt; bool {
       if self.is_open() || !self.bonus_done() {
           return true;
       }

       if self.is_spare() {
           return self.bonus_score() &lt;= 10;
       }

       if let Some(first) = self.bonus.iter().next() {
           if *first == 10 {
               self.bonus_score() &lt;= 20
           } else {
               self.bonus_score() &lt;= 10
           }
       } else {
           unreachable!();
       }
   }

   fn is_complete(&amp;self) -&gt; bool {
       self.is_open() || self.bonus_done()
   }

   fn rolls_done(&amp;self) -&gt; bool {
       self.rolls.len() == 2 || self.is_strike()
   }

   fn bonus_done(&amp;self) -&gt; bool {
       (self.is_spare() &amp;&amp; self.bonus.len() == 1) || (self.is_strike() &amp;&amp; self.bonus.len() == 2)
   }

   fn is_open(&amp;self) -&gt; bool {
       self.rolls.len() == 2 &amp;&amp; self.roll_score() &lt; 10
   }

   fn is_spare(&amp;self) -&gt; bool {
       self.rolls.len() == 2 &amp;&amp; self.roll_score() == 10
   }

   fn is_strike(&amp;self) -&gt; bool {
       self.rolls.len() == 1 &amp;&amp; self.roll_score() == 10
   }

   fn add_roll(&amp;mut self, roll: u16) {
       if !self.is_complete() {
           if self.is_spare() || self.is_strike() {
               self.bonus.push(roll)
           } else {
               self.rolls.push(roll)
           }
       }
   }

   fn new() -&gt; Self {
       Frame {
           rolls: vec![],
           bonus: vec![],
       }
   }
}

impl BowlingGame {
   pub fn new() -&gt; Self {
       BowlingGame {
           frames: vec![Frame::new()],
       }
   }

   pub fn roll(&amp;mut self, pins: u16) -&gt; Result&lt;(), Error&gt; {
       if pins &gt; 10 {
           Err(Error::NotEnoughPinsLeft)
       } else {
           if self.score().is_some() {
               return Err(Error::GameComplete);
           }

           for frame in self.frames.iter_mut() {
               frame.add_roll(pins)
           }

           if self.frames.iter().any(|f| !f.is_valid()) {
               return Err(Error::NotEnoughPinsLeft);
           }

           if self.frames.iter().last().unwrap().rolls_done() &amp;&amp; self.frames.len() &lt; 10 {
               self.frames.push(Frame::new());
           }

           Ok(())
       }
   }

   pub fn score(&amp;self) -&gt; Option&lt;u16&gt; {
       if !self.is_done() {
           None
       } else {
           Some(self.frames.iter().fold(0, |acc, r| acc + r.score()))
       }
   }

   fn is_done(&amp;self) -&gt; bool {
       self.frames.len() == 10 &amp;&amp; self.frames.iter().all(|f| f.is_complete())
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-55" id="填充相关-55"><h2>填充/相关</h2></a>
<a class="header" href="#sublist" id="sublist"><h1>Sublist</h1></a>
<a class="header" href="#1-readme-56" id="1-readme-56"><h2>1. Readme</h2></a>
<a class="header" href="#子列表" id="子列表"><h1>子列表</h1></a>
<p>给定两个列表确定第一个列表是否包含在第二个列表中；第二个列表是否包含在第一个列表中；两个列表是否包含在彼此，或者这些都不是真的。</p>
<p>具体来说，列表 A 是列表 B 的子列表，在于是否 B 的前面删除 0 个或更多元素和 B 的后面删除 0 个或更多元素，则得到完全等于 A 的列表。</p>
<p>例子:</p>
<ul>
<li>A = <code>[1,2,3]</code>，B = <code>[1,2,3,4,5]</code>，A 是 B 的子列表</li>
<li>A = <code>[3,4,5]</code>，B = <code>[1,2,3,4,5]</code>，A 是 B 的子列表</li>
<li>A = <code>[3,4]</code>，B = <code>[1,2,3,4,5]</code>，A 是 B 的子列表</li>
<li>A = <code>[1,2,3]</code>，B = <code>[1,2,3]</code>，A 等于 B。</li>
<li>A = <code>[1,2,3,4,5]</code>，B = <code>[2,3,4]</code>，A 是 B 的父列表</li>
<li>A = <code>[1,2,4]</code>，B = <code>[1,2,3,4,5]</code>，A 不是 B 的父列表，子列表，或等于 B 的列表</li>
</ul>
<a class="header" href="#2-开始你的表演-56" id="2-开始你的表演-56"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">#[derive(Debug, PartialEq)]
pub enum Comparison {
   Equal,
   Sublist,
   Superlist,
   Unequal,
}

pub fn sublist&lt;T: PartialEq&gt;(_first_list: &amp;[T], _second_list: &amp;[T]) -&gt; Comparison {
   unimplemented!(&quot;Determine if the first list is equal to, sublist of, superlist of or unequal to the second list.&quot;);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-56" id="3-测试代码查看-56"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]

#fn main() {
#[test]
fn empty_equals_empty() {
   let v: &amp;[u32] = &amp;[];

   assert_eq!(Comparison::Equal, sublist(&amp;v, &amp;v));
}

#[test]
//#[ignore]
fn test_empty_is_a_sublist_of_anything() {
   assert_eq!(Comparison::Sublist, sublist(&amp;[], &amp;['a', 's', 'd', 'f']));
}

#[test]
//#[ignore]
fn test_anything_is_a_superlist_of_empty() {
   assert_eq!(Comparison::Superlist, sublist(&amp;['a', 's', 'd', 'f'], &amp;[]));
}

#[test]
//#[ignore]
fn test_1_is_not_2() {
   assert_eq!(Comparison::Unequal, sublist(&amp;[1], &amp;[2]));
}

#[test]
//#[ignore]
fn test_compare_larger_equal_lists() {
   use std::iter::repeat;

   let v: Vec&lt;char&gt; = repeat('x').take(1000).collect();

   assert_eq!(Comparison::Equal, sublist(&amp;v, &amp;v));
}

#[test]
//#[ignore]
fn test_sublist_at_start() {
   assert_eq!(Comparison::Sublist, sublist(&amp;[1, 2, 3], &amp;[1, 2, 3, 4, 5]));
}

#[test]
//#[ignore]
fn sublist_in_middle() {
   assert_eq!(Comparison::Sublist, sublist(&amp;[4, 3, 2], &amp;[5, 4, 3, 2, 1]));
}

#[test]
//#[ignore]
fn sublist_at_end() {
   assert_eq!(Comparison::Sublist, sublist(&amp;[3, 4, 5], &amp;[1, 2, 3, 4, 5]));
}

#[test]
//#[ignore]
fn partially_matching_sublist_at_start() {
   assert_eq!(Comparison::Sublist, sublist(&amp;[1, 1, 2], &amp;[1, 1, 1, 2]));
}

#[test]
//#[ignore]
fn sublist_early_in_huge_list() {
   let huge: Vec&lt;u32&gt; = (1..1000000).collect();

   assert_eq!(Comparison::Sublist, sublist(&amp;[3, 4, 5], &amp;huge));
}

#[test]
//#[ignore]
fn huge_sublist_not_in_huge_list() {
   let v1: Vec&lt;u64&gt; = (10..1000001).collect();
   let v2: Vec&lt;u64&gt; = (1..1000000).collect();

   assert_eq!(Comparison::Unequal, sublist(&amp;v1, &amp;v2));
}

#[test]
//#[ignore]
fn superlist_at_start() {
   assert_eq!(Comparison::Superlist, sublist(&amp;[1, 2, 3, 4, 5], &amp;[1, 2, 3]));
}

#[test]
//#[ignore]
fn superlist_in_middle() {
   assert_eq!(Comparison::Superlist, sublist(&amp;[5, 4, 3, 2, 1], &amp;[4, 3, 2]));
}

#[test]
//#[ignore]
fn superlist_at_end() {
   assert_eq!(Comparison::Superlist, sublist(&amp;[1, 2, 3, 4, 5], &amp;[3, 4, 5]));
}

#[test]
//#[ignore]
fn superlist_early_in_huge_list() {
   let huge: Vec&lt;u32&gt; = (1..1000000).collect();

   assert_eq!(Comparison::Superlist, sublist(&amp;huge, &amp;[3, 4, 5]));
}

#[test]
//#[ignore]
fn recurring_values_sublist() {
   assert_eq!(
       Comparison::Sublist,
       sublist(&amp;[1, 2, 1, 2, 3], &amp;[1, 2, 3, 1, 2, 1, 2, 3, 2, 1])
   );
}

#[test]
//#[ignore]
fn recurring_values_unequal() {
   assert_eq!(
       Comparison::Unequal,
       sublist(&amp;[1, 2, 1, 2, 3], &amp;[1, 2, 3, 1, 2, 3, 2, 3, 2, 1])
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-56" id="4-答案-56"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[derive(PartialEq, Eq, Debug)]
pub enum Comparison {
   Equal,
   Sublist,
   Superlist,
   Unequal,
}

pub fn sublist&lt;T: PartialEq&gt;(a: &amp;[T], b: &amp;[T]) -&gt; Comparison {
   if a == b {
       Comparison::Equal
   } else if contains(a, b) {
       Comparison::Superlist
   } else if contains(b, a) {
       Comparison::Sublist
   } else {
       Comparison::Unequal
   }
}

fn contains&lt;T: PartialEq&gt;(a: &amp;[T], b: &amp;[T]) -&gt; bool {
   if a.len() &lt; b.len() {
       return false;
   }

   if a.starts_with(b) {
       return true;
   }

   contains(&amp;a[1..], b)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-56" id="填充相关-56"><h2>填充/相关</h2></a>
<a class="header" href="#space-age" id="space-age"><h1>Space Age</h1></a>
<a class="header" href="#1-readme-57" id="1-readme-57"><h2>1. Readme</h2></a>
<a class="header" href="#地球年" id="地球年"><h1>地球年</h1></a>
<p>给定年龄(以秒为单位)，计算某人的年龄:</p>
<ul>
<li>地球：轨道周期 365.25 地球日,或 31557600 秒</li>
<li>水星：轨道周期 0.2408467 地球年</li>
<li>金星：轨道周期 0.61519726 地球年</li>
<li>火星：轨道周期 1.8808158 地球年</li>
<li>木星：轨道周期 11.862615 地球年</li>
<li>土星：轨道周期 29.447498 地球年</li>
<li>天王星：轨道周期 84.016846 地球年</li>
<li>海王星：轨道周期 164.79132 地球年</li>
</ul>
<p>因此，如果你被告知某人的年龄为 1,000,000,000 秒，你应该可以说它们的年龄为 31.69 地球年.</p>
<p>如果你想知道为什么冥王星没有加入进来，请去观看<a href="http://www.youtube.com/watch?v=Z_2gbGXzFbs">this youtube video</a>.</p>
<a class="header" href="#主题" id="主题"><h1>主题</h1></a>
<p>在解决此问题时，您可能想要阅读的一些 Rust 主题:</p>
<ul>
<li>Trait，用 From trait 实现，或实现自己的 trait</li>
<li>trait 的默认方法实现</li>
</ul>
<a class="header" href="#资源-44" id="资源-44"><h2>资源</h2></a>
<p>部分灵感来自 Chris Pine 在线学习编程教程的第 1 章.<a href="http://pine.fm/LearnToProgram/?Chapter=01">http://pine.fm/LearnToProgram/?Chapter=01</a></p>
<a class="header" href="#2-开始你的表演-57" id="2-开始你的表演-57"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">// The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.

#[derive(Debug)]
pub struct Duration;

impl From&lt;u64&gt; for Duration {
   fn from(s: u64) -&gt; Self {
       unimplemented!(&quot;s, measured in seconds: {}&quot;, s)
   }
}

pub trait Planet {
   fn years_during(d: &amp;Duration) -&gt; f64 {
       unimplemented!(
           &quot;convert a duration ({:?}) to the number of years on this planet for that duration&quot;,
           d,
       );
   }
}

pub struct Mercury;
pub struct Venus;
pub struct Earth;
pub struct Mars;
pub struct Jupiter;
pub struct Saturn;
pub struct Uranus;
pub struct Neptune;

impl Planet for Mercury {}
impl Planet for Venus {}
impl Planet for Earth {}
impl Planet for Mars {}
impl Planet for Jupiter {}
impl Planet for Saturn {}
impl Planet for Uranus {}
impl Planet for Neptune {}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-57" id="3-测试代码查看-57"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn assert_in_delta(expected: f64, actual: f64) {
   let diff: f64 = (expected - actual).abs();
   let delta: f64 = 0.01;
   if diff &gt; delta {
       panic!(
           &quot;Your result of {} should be within {} of the expected result {}&quot;,
           actual, delta, expected
       )
   }
}

#[test]
fn earth_age() {
   let duration = Duration::from(1_000_000_000);
   assert_in_delta(31.69, Earth::years_during(&amp;duration));
}

#[test]
//#[ignore]
fn mercury_age() {
   let duration = Duration::from(2_134_835_688);
   assert_in_delta(280.88, Mercury::years_during(&amp;duration));
}

#[test]
//#[ignore]
fn venus_age() {
   let duration = Duration::from(189_839_836);
   assert_in_delta(9.78, Venus::years_during(&amp;duration));
}

#[test]
//#[ignore]
fn mars_age() {
   let duration = Duration::from(2_329_871_239);
   assert_in_delta(39.25, Mars::years_during(&amp;duration));
}

#[test]
//#[ignore]
fn jupiter_age() {
   let duration = Duration::from(901_876_382);
   assert_in_delta(2.41, Jupiter::years_during(&amp;duration));
}

#[test]
//#[ignore]
fn saturn_age() {
   let duration = Duration::from(3_000_000_000);
   assert_in_delta(3.23, Saturn::years_during(&amp;duration));
}

#[test]
//#[ignore]
fn uranus_age() {
   let duration = Duration::from(3_210_123_456);
   assert_in_delta(1.21, Uranus::years_during(&amp;duration));
}

#[test]
//#[ignore]
fn neptune_age() {
   let duration = Duration::from(8_210_123_456);
   assert_in_delta(1.58, Neptune::years_during(&amp;duration));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-57" id="4-答案-57"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub struct Duration {
   seconds: f64,
}

impl From&lt;u64&gt; for Duration {
   fn from(s: u64) -&gt; Self {
       Duration { seconds: s as f64 }
   }
}

impl From&lt;f64&gt; for Duration {
   fn from(s: f64) -&gt; Self {
       Duration { seconds: s }
   }
}

pub trait Planet {
   fn orbital_duration() -&gt; Duration;
   fn years_during(d: &amp;Duration) -&gt; f64 {
       d.seconds / Self::orbital_duration().seconds
   }
}

pub struct Mercury;
pub struct Venus;
pub struct Earth;
pub struct Mars;
pub struct Jupiter;
pub struct Saturn;
pub struct Uranus;
pub struct Neptune;

impl Planet for Mercury {
   fn orbital_duration() -&gt; Duration {
       Duration::from(7600543.81992)
   }
}

impl Planet for Venus {
   fn orbital_duration() -&gt; Duration {
       Duration::from(19414149.052176)
   }
}

impl Planet for Earth {
   fn orbital_duration() -&gt; Duration {
       Duration::from(31557600)
   }
}

impl Planet for Mars {
   fn orbital_duration() -&gt; Duration {
       Duration::from(59354032.69008)
   }
}

impl Planet for Jupiter {
   fn orbital_duration() -&gt; Duration {
       Duration::from(374355659.124)
   }
}

impl Planet for Saturn {
   fn orbital_duration() -&gt; Duration {
       Duration::from(929292362.8848)
   }
}

impl Planet for Uranus {
   fn orbital_duration() -&gt; Duration {
       Duration::from(2651370019.3296)
   }
}

impl Planet for Neptune {
   fn orbital_duration() -&gt; Duration {
       Duration::from(5200418560.032)
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-57" id="填充相关-57"><h2>填充/相关</h2></a>
<a class="header" href="#luhn-trait" id="luhn-trait"><h1>Luhn Trait</h1></a>
<a class="header" href="#1-readme-58" id="1-readme-58"><h2>1. Readme</h2></a>
<a class="header" href="#鲁恩-trait" id="鲁恩-trait"><h1>鲁恩 trait</h1></a>
<a class="header" href="#luhn-使用自定义-trait" id="luhn-使用自定义-trait"><h1>Luhn: 使用自定义 trait</h1></a>
<p>在做这个练习之前，你应该做原始的 luhn 练习和进阶练习，”luhn:使用 From trait”.</p>
<p>要获得原始的 Luhn 练习，运行</p>
<pre><code class="language-shell">exercism download --exercise=luhn --track=rust
</code></pre>
<p>要获得”Lunn:使用 From trait”的练习，运行</p>
<pre><code class="language-shell">exercism download --exercise=luhn-from --track=rust
</code></pre>
<p>在原始的 luhn 练习中，您只验证字符串，但 luhn 算法也可以应用于整数。</p>
<p>在”Lurn:使用 From trait”中，你实现了一个 From trait，还需要你创建一个 luhn 结构。</p>
<p>要是不创建一个结构来执行验证呢，如果要您自己验证了原语本身(即，String，u8 等)呢?</p>
<p>在本练习中，您将创建并实现自定义<a href="https://doc.rust-lang.org/book/ch10-02-traits.html">trait</a>，来执行验证.</p>
<p>注:它是<a href="https://kaisery.github.io/trpl-zh-cn/ch10-02-traits.html#a%E4%B8%BA%E7%B1%BB%E5%9E%8B%E5%AE%9E%E7%8E%B0-trait">实现原语的 trait，不是 Rust 的习惯</a>。 在这个练习中，我们展示了一些你<em>可以</em>做的东西，而不是你<em>应该</em>做的东西。如果你发现自己在原语上实现了 trait，也许你有一个<a href="http://wiki.c2.com/?PrimitiveObsession">Primitive Obsession</a>例子。</p>
<a class="header" href="#资源-45" id="资源-45"><h2>资源</h2></a>
<p>基于原始 luhn 练习，延续 Rust 轨迹</p>
<a class="header" href="#2-开始你的表演-58" id="2-开始你的表演-58"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub trait Luhn {
   fn valid_luhn(&amp;self) -&gt; bool;
}

/// Here is the example of how to implement custom Luhn trait
/// for the &amp;str type. Naturally, you can implement this trait
/// by hand for the every other type presented in the test suite,
/// but your solution will fail if a new type is presented.
/// Perhaps there exists a better solution for this problem?
impl&lt;'a&gt; Luhn for &amp;'a str {
   fn valid_luhn(&amp;self) -&gt; bool {
       unimplemented!(&quot;Determine if '{}' is a valid credit card number.&quot;, self);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-58" id="3-测试代码查看-58"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn you_can_validate_from_a_str() {
   assert!(&quot;046 454 286&quot;.valid_luhn());
   assert!(!&quot;046 454 287&quot;.valid_luhn());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_string() {
   assert!(String::from(&quot;046 454 286&quot;).valid_luhn());
   assert!(!String::from(&quot;046 454 287&quot;).valid_luhn());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_u8() {
   assert!(240u8.valid_luhn());
   assert!(!241u8.valid_luhn());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_u16() {
   let valid = 64_436u16;
   let invalid = 64_437u16;
   assert!(valid.valid_luhn());
   assert!(!invalid.valid_luhn());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_u32() {
   let valid = 46_454_286u32;
   let invalid = 46_454_287u32;
   assert!(valid.valid_luhn());
   assert!(!invalid.valid_luhn());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_u64() {
   let valid = 8273_1232_7352_0562u64;
   let invalid = 8273_1232_7352_0569u64;
   assert!(valid.valid_luhn());
   assert!(!invalid.valid_luhn());
}

#[test]
//#[ignore]
fn you_can_validate_from_a_usize() {
   let valid = 8273_1232_7352_0562usize;
   let invalid = 8273_1232_7352_0569usize;
   assert!(valid.valid_luhn());
   assert!(!invalid.valid_luhn());
}

#}</code></pre></pre>
<a class="header" href="#4-答案-58" id="4-答案-58"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub trait Luhn {
   fn valid_luhn(&amp;self) -&gt; bool;
}

impl Luhn for String {
   fn valid_luhn(&amp;self) -&gt; bool {
       if self.chars().any(|c| c.is_alphabetic()) || self.chars().count() == 1 {
           return false;
       }

       self.chars()
           .filter_map(|c| c.to_digit(10))
           .rev()
           .enumerate()
           .map(|(index, digit)| if index % 2 == 0 { digit } else { digit * 2 })
           .map(|digit| if digit &gt; 9 { digit - 9 } else { digit })
           .sum::&lt;u32&gt;() % 10 == 0
   }
}

impl&lt;'a&gt; Luhn for &amp;'a str {
   fn valid_luhn(&amp;self) -&gt; bool {
       String::from(*self).valid_luhn()
   }
}

impl Luhn for u8 {
   fn valid_luhn(&amp;self) -&gt; bool {
       self.to_string().valid_luhn()
   }
}

impl Luhn for u16 {
   fn valid_luhn(&amp;self) -&gt; bool {
       self.to_string().valid_luhn()
   }
}

impl Luhn for u32 {
   fn valid_luhn(&amp;self) -&gt; bool {
       self.to_string().valid_luhn()
   }
}

impl Luhn for u64 {
   fn valid_luhn(&amp;self) -&gt; bool {
       self.to_string().valid_luhn()
   }
}

impl Luhn for usize {
   fn valid_luhn(&amp;self) -&gt; bool {
       self.to_string().valid_luhn()
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-58" id="填充相关-58"><h2>填充/相关</h2></a>
<a class="header" href="#macros" id="macros"><h1>Macros</h1></a>
<a class="header" href="#1-readme-59" id="1-readme-59"><h2>1. Readme</h2></a>
<a class="header" href="#宏" id="宏"><h1>宏</h1></a>
<p>宏是 Rust 程序员工具箱中的一个强大工具，要想对它有个简单认知，可以看看<a href="https://doc.rust-lang.org/reference/macros-by-example.html">宏例子</a>。让我们写一个!</p>
<a class="header" href="#问题陈述" id="问题陈述"><h2>问题陈述</h2></a>
<p>你可以用<code>vec![]</code>内联宏，生产一个任意长度的<code>Vec</code>。然而,Rust 并没有生产<a href="https://doc.rust-lang.org/std/collections/struct.HashMap.html"><code>HashMap</code></a>的内联宏<code>hashmap!()</code>。</p>
<p>例如，您的库的用户可能会编写<code>hashmap!('a' =&gt; 3, 'b' =&gt; 11, 'z' =&gt; 32)</code>。这应该扩展到以下代码:</p>
<pre><pre class="playpen"><code class="language-rust no_run">
# #![allow(unused_variables)]
#fn main() {
{
   let mut hm = HashMap::new();
   hm.insert('a', 3);
   hm.insert('b', 11);
   hm.insert('z', 32);
   hm
}
#}</code></pre></pre>
<p>注意<a href="https://crates.io/crates/maplit"><code>maplit</code>箱子</a>时提供了一个很好地解决这个问题的宏。但请执行您自己的解决方案，而不是使用这个箱子，请在查看箱子源代码之前，自己尝试下。</p>
<a class="header" href="#资源-46" id="资源-46"><h2>资源</h2></a>
<p>Peter Goodspeed-Niklaus</p>
<a class="header" href="#2-开始你的表演-59" id="2-开始你的表演-59"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">#[macro_export]
macro_rules! hashmap {
   () =&gt; {
       unimplemented!()
   };
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-59" id="3-测试代码查看-59"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[macro_use]
use std::collections::HashMap;

#[test]
fn test_empty() {
   let expected: HashMap&lt;u32, u32&gt; = HashMap::new();
   let computed: HashMap&lt;u32, u32&gt; = hashmap!();
   assert_eq!(computed, expected);
}

#[test]
//#[ignore]
fn test_no_trailing_comma() {
   let mut expected = HashMap::new();
   expected.insert(1, &quot;one&quot;);
   expected.insert(2, &quot;two&quot;);
   assert_eq!(hashmap!(1 =&gt; &quot;one&quot;, 2 =&gt; &quot;two&quot;), expected);
}

#[test]
//#[ignore]
fn test_trailing_comma() {
   let mut expected = HashMap::new();
   expected.insert('h', 89);
   expected.insert('a', 1);
   expected.insert('s', 19);
   expected.insert('h', 8);
   assert_eq!(
       hashmap!(
           'h' =&gt; 89,
           'a' =&gt; 1,
           's' =&gt; 19,
           'h' =&gt; 8,
       ),
       expected
   );
}

#[test]
//#[ignore]
fn test_nested() {
   let mut expected = HashMap::new();
   expected.insert(&quot;non-empty&quot;, {
       let mut subhashmap = HashMap::new();
       subhashmap.insert(23, 623);
       subhashmap.insert(34, 21);
       subhashmap
   });
   expected.insert(&quot;empty&quot;, HashMap::new());
   assert_eq!(
       hashmap!(
           &quot;non-empty&quot; =&gt; hashmap!(
               23 =&gt; 623,
               34 =&gt; 21
           ),
           &quot;empty&quot; =&gt; hashmap!()
       ),
       expected
   );
}

mod test {
   #[test]
   //#[ignore]
   fn type_not_in_scope() {
       let _expected: ::std::collections::HashMap&lt;(), ()&gt; = hashmap!();
   }
}

#}</code></pre></pre>
<a class="header" href="#4-答案-59" id="4-答案-59"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// Ignoring the README's injunction, this is heavily based on the implementation from maplit.
// Original source is at https://github.com/bluss/maplit/blob/master/src/lib.rs#L27-L60

#[macro_export]
macro_rules! hashmap {
   ($($key:expr =&gt; $value:expr,)+) =&gt; { hashmap!($($key =&gt; $value),+) };
   ($($key:expr =&gt; $value:expr),*) =&gt; {
       {
           let mut _map = ::std::collections::HashMap::new();
           $(
               _map.insert($key, $value);
           )*
           _map
       }
   };
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-59" id="填充相关-59"><h2>填充/相关</h2></a>
<a class="header" href="#allergies" id="allergies"><h1>Allergies</h1></a>
<a class="header" href="#1-readme-60" id="1-readme-60"><h2>1. Readme</h2></a>
<a class="header" href="#过敏" id="过敏"><h1>过敏</h1></a>
<p>给出一个人的过敏分，确定他们是否对某一物品过敏，以及他们的过敏列表.</p>
<p>过敏测试产生单个数字分数，其中包含有关该人所有过敏的信息(他们进行了测试)。</p>
<p>测试的物品列表(及其值)为:</p>
<ul>
<li>鸡蛋(1)</li>
<li>花生(2)</li>
<li>贝类(4)</li>
<li>草莓(8)</li>
<li>西红柿(16)</li>
<li>巧克力(32)</li>
<li>花粉(64)</li>
<li>猫(128)</li>
</ul>
<p>因此，如果汤姆对花生和巧克力过敏，他会得到 34 分.</p>
<p>现在，只要得到 34 分，你的程序应该说:</p>
<ul>
<li>汤姆是否对上面列出的任何一种过敏原过敏.</li>
<li>汤姆所有过敏原。</li>
</ul>
<p>注意：给出的分数可能<strong>不</strong>包括上面列出的过敏原(即分数为 256，512，1024 等的过敏原)。您的程序应忽略这些组成部分。例如，如果过敏分数是 257，您的程序应该只报告鸡蛋(1)过敏。</p>
<a class="header" href="#资源-47" id="资源-47"><h2>资源</h2></a>
<p>Jumpstart 实验室热身<a href="http://jumpstartlab.com">http://jumpstartlab.com</a></p>
<a class="header" href="#2-开始你的表演-60" id="2-开始你的表演-60"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub struct Allergies;

#[derive(Debug, PartialEq)]
pub enum Allergen {
   Eggs,
   Peanuts,
   Shellfish,
   Strawberries,
   Tomatoes,
   Chocolate,
   Pollen,
   Cats,
}

impl Allergies {
   pub fn new(score: u32) -&gt; Self {
       unimplemented!(
           &quot;Given the '{}' score, construct a new Allergies struct.&quot;,
           score
       );
   }

   pub fn is_allergic_to(&amp;self, allergen: &amp;Allergen) -&gt; bool {
       unimplemented!(
           &quot;Determine if the patient is allergic to the '{:?}' allergen.&quot;,
           allergen
       );
   }

   pub fn allergies(&amp;self) -&gt; Vec&lt;Allergen&gt; {
       unimplemented!(&quot;Return the list of allergens contained within the score with which the Allergies struct was made.&quot;);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-60" id="3-测试代码查看-60"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn compare_allergy_vectors(expected: &amp;[Allergen], actual: &amp;[Allergen]) {
   for element in expected {
       if !actual.contains(element) {
           panic!(
               &quot;Allergen missing\n  {:?} should be in {:?}&quot;,
               element, actual
           );
       }
   }

   if actual.len() != expected.len() {
       panic!(
           &quot;Allergy vectors are of different lengths\n  expected {:?}\n  got {:?}&quot;,
           expected, actual
       );
   }
}

#[test]
fn is_not_allergic_to_anything() {
   let allergies = Allergies::new(0);
   assert!(!allergies.is_allergic_to(&amp;Allergen::Peanuts));
   assert!(!allergies.is_allergic_to(&amp;Allergen::Cats));
   assert!(!allergies.is_allergic_to(&amp;Allergen::Strawberries));
}

#[test]
//#[ignore]
fn is_allergic_to_eggs() {
   assert!(Allergies::new(1).is_allergic_to(&amp;Allergen::Eggs));
}

#[test]
//#[ignore]
fn is_allergic_to_egg_shellfish_and_strawberries() {
   let allergies = Allergies::new(5);
   assert!(allergies.is_allergic_to(&amp;Allergen::Eggs));
   assert!(allergies.is_allergic_to(&amp;Allergen::Shellfish));
   assert!(!allergies.is_allergic_to(&amp;Allergen::Strawberries));
}

#[test]
//#[ignore]
fn no_allergies_at_all() {
   let expected = &amp;[];
   let allergies = Allergies::new(0).allergies();

   compare_allergy_vectors(expected, &amp;allergies);
}

#[test]
//#[ignore]
fn allergic_to_just_eggs() {
   let expected = &amp;[Allergen::Eggs];
   let allergies = Allergies::new(1).allergies();

   compare_allergy_vectors(expected, &amp;allergies);
}

#[test]
//#[ignore]
fn allergic_to_just_peanuts() {
   let expected = &amp;[Allergen::Peanuts];
   let allergies = Allergies::new(2).allergies();

   compare_allergy_vectors(expected, &amp;allergies);
}

#[test]
//#[ignore]
fn allergic_to_just_strawberries() {
   let expected = &amp;[Allergen::Strawberries];
   let allergies = Allergies::new(8).allergies();

   compare_allergy_vectors(expected, &amp;allergies);
}

#[test]
//#[ignore]
fn allergic_to_eggs_and_peanuts() {
   let expected = &amp;[Allergen::Eggs, Allergen::Peanuts];
   let allergies = Allergies::new(3).allergies();

   compare_allergy_vectors(expected, &amp;allergies);
}

#[test]
//#[ignore]
fn allergic_to_eggs_and_shellfish() {
   let expected = &amp;[Allergen::Eggs, Allergen::Shellfish];
   let allergies = Allergies::new(5).allergies();

   compare_allergy_vectors(expected, &amp;allergies);
}

#[test]
//#[ignore]
fn allergic_to_many_things() {
   let expected = &amp;[
       Allergen::Strawberries,
       Allergen::Tomatoes,
       Allergen::Chocolate,
       Allergen::Pollen,
       Allergen::Cats,
   ];
   let allergies = Allergies::new(248).allergies();

   compare_allergy_vectors(expected, &amp;allergies);
}

#[test]
//#[ignore]
fn allergic_to_everything() {
   let expected = &amp;[
       Allergen::Eggs,
       Allergen::Peanuts,
       Allergen::Shellfish,
       Allergen::Strawberries,
       Allergen::Tomatoes,
       Allergen::Chocolate,
       Allergen::Pollen,
       Allergen::Cats,
   ];
   let allergies = Allergies::new(255).allergies();

   compare_allergy_vectors(expected, &amp;allergies);
}

#[test]
//#[ignore]
fn scores_over_255_do_not_trigger_false_positives() {
   let expected = &amp;[
       Allergen::Eggs,
       Allergen::Shellfish,
       Allergen::Strawberries,
       Allergen::Tomatoes,
       Allergen::Chocolate,
       Allergen::Pollen,
       Allergen::Cats,
   ];
   let allergies = Allergies::new(509).allergies();

   compare_allergy_vectors(expected, &amp;allergies);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-60" id="4-答案-60"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub struct Allergies(pub usize);

#[derive(PartialEq, Debug)]
pub enum Allergen {
   Eggs,
   Peanuts,
   Shellfish,
   Strawberries,
   Tomatoes,
   Chocolate,
   Pollen,
   Cats,
}

impl Allergies {
   pub fn new(score: usize) -&gt; Allergies {
       Allergies(score)
   }

   pub fn is_allergic_to(&amp;self, allergen: &amp;Allergen) -&gt; bool {
       let allergens = Allergies::allergens();
       let index = allergens
           .iter()
           .position(|x: &amp;Allergen| x == allergen)
           .unwrap();
       (self.0 &amp; (1 &lt;&lt; index)) != 0
   }

   pub fn allergies(&amp;self) -&gt; Vec&lt;Allergen&gt; {
       Allergies::allergens()
           .into_iter()
           .filter(|allergen| self.is_allergic_to(allergen))
           .collect()
   }

   fn allergens() -&gt; Vec&lt;Allergen&gt; {
       vec![
           Allergen::Eggs,
           Allergen::Peanuts,
           Allergen::Shellfish,
           Allergen::Strawberries,
           Allergen::Tomatoes,
           Allergen::Chocolate,
           Allergen::Pollen,
           Allergen::Cats,
       ]
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-60" id="填充相关-60"><h2>填充/相关</h2></a>
<a class="header" href="#variable-length-quantity" id="variable-length-quantity"><h1>Variable Length Quantity</h1></a>
<a class="header" href="#1-readme-61" id="1-readme-61"><h2>1. Readme</h2></a>
<a class="header" href="#可变长度数量" id="可变长度数量"><h1>可变长度数量</h1></a>
<p>实现可变长度数量编码和解码.</p>
<p>这项工作的目标是实现<a href="https://en.wikipedia.org/wiki/Variable-length_quantity">VLQ</a>的编码/解码。</p>
<p>简而言之，此编码的目标是以节省字节的方式，对整数值进行编码。只有每个字节的前 7 位是有效的(右对齐；有点像 ASCII 字节)。因此，如果您有 32 位值，则必须解开为一系列 7 位字节。当然，根据您的整数，您将拥有可变数量的字节。要指出哪个是系列的最后一个字节，请将 #7 位清零。而所有前面的字节中，您都要设置#7 位。</p>
<p>所以，如果一个整数介于<code>0-127</code>，它可以表示为一个字节。虽然 VLQ 可以处理任意大小的数字，但对于本练习，我们将仅限于适合 32 位无符号整数的数字。以下是整数作为 32 位值的示例，以及它们转换为的可变长度数量:</p>
<pre><code class="language-text"> NUMBER        VARIABLE QUANTITY
00000000              00
00000040              40
0000007F              7F
00000080             81 00
00002000             C0 00
00003FFF             FF 7F
00004000           81 80 00
00100000           C0 80 00
001FFFFF           FF FF 7F
00200000          81 80 80 00
08000000          C0 80 80 00
0FFFFFFF          FF FF FF 7F
</code></pre>
<a class="header" href="#资源-48" id="资源-48"><h2>资源</h2></a>
<p>一个糟糕的 Splice 开发人员，必须实现 MIDI 编码/解码.<a href="https://splice.com">https://splice.com</a></p>
<a class="header" href="#2-开始你的表演-61" id="2-开始你的表演-61"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">#[derive(Debug, PartialEq)]
pub enum Error {
   IncompleteNumber,
   Overflow,
}

/// Convert a list of numbers to a stream of bytes encoded with variable length encoding.
pub fn to_bytes(values: &amp;[u32]) -&gt; Vec&lt;u8&gt; {
   unimplemented!(&quot;Convert the values {:?} to a list of bytes&quot;, values)
}

/// Given a stream of bytes, extract all numbers which are encoded in there.
pub fn from_bytes(bytes: &amp;[u8]) -&gt; Result&lt;Vec&lt;u32&gt;, Error&gt; {
   unimplemented!(&quot;Convert the list of bytes {:?} to a list of numbers&quot;, bytes)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-61" id="3-测试代码查看-61"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn to_single_byte() {
   assert_eq!(&amp;[0x00], to_bytes(&amp;[0x00]).as_slice());
   assert_eq!(&amp;[0x40], to_bytes(&amp;[0x40]).as_slice());
   assert_eq!(&amp;[0x7f], to_bytes(&amp;[0x7f]).as_slice());
}

#[test]
//#[ignore]
fn to_double_byte() {
   assert_eq!(&amp;[0x81, 0x00], to_bytes(&amp;[0x80]).as_slice());
   assert_eq!(&amp;[0xc0, 0x00], to_bytes(&amp;[0x2000]).as_slice());
   assert_eq!(&amp;[0xff, 0x7f], to_bytes(&amp;[0x3fff]).as_slice());
}

#[test]
//#[ignore]
fn to_triple_byte() {
   assert_eq!(&amp;[0x81, 0x80, 0x00], to_bytes(&amp;[0x4000]).as_slice());
   assert_eq!(&amp;[0xc0, 0x80, 0x00], to_bytes(&amp;[0x10_0000]).as_slice());
   assert_eq!(&amp;[0xff, 0xff, 0x7f], to_bytes(&amp;[0x1f_ffff]).as_slice());
}

#[test]
//#[ignore]
fn to_quadruple_byte() {
   assert_eq!(&amp;[0x81, 0x80, 0x80, 0x00], to_bytes(&amp;[0x20_0000]).as_slice());
   assert_eq!(
       &amp;[0xc0, 0x80, 0x80, 0x00],
       to_bytes(&amp;[0x0800_0000]).as_slice()
   );
   assert_eq!(
       &amp;[0xff, 0xff, 0xff, 0x7f],
       to_bytes(&amp;[0x0fff_ffff]).as_slice()
   );
}

#[test]
//#[ignore]
fn to_quintuple_byte() {
   assert_eq!(
       &amp;[0x81, 0x80, 0x80, 0x80, 0x00],
       to_bytes(&amp;[0x1000_0000]).as_slice()
   );
   assert_eq!(
       &amp;[0x8f, 0xf8, 0x80, 0x80, 0x00],
       to_bytes(&amp;[0xff00_0000]).as_slice()
   );
   assert_eq!(
       &amp;[0x8f, 0xff, 0xff, 0xff, 0x7f],
       to_bytes(&amp;[0xffff_ffff]).as_slice()
   );
}

#[test]
//#[ignore]
fn from_bytes_test() {
   assert_eq!(Ok(vec![0x7f]), from_bytes(&amp;[0x7f]));
   assert_eq!(Ok(vec![0x2000]), from_bytes(&amp;[0xc0, 0x00]));
   assert_eq!(Ok(vec![0x1f_ffff]), from_bytes(&amp;[0xff, 0xff, 0x7f]));
   assert_eq!(Ok(vec![0x20_0000]), from_bytes(&amp;[0x81, 0x80, 0x80, 0x00]));
   assert_eq!(
       Ok(vec![0xffff_ffff]),
       from_bytes(&amp;[0x8f, 0xff, 0xff, 0xff, 0x7f])
   );
}

#[test]
//#[ignore]
fn to_bytes_multiple_values() {
   assert_eq!(&amp;[0x40, 0x7f], to_bytes(&amp;[0x40, 0x7f]).as_slice());
   assert_eq!(
       &amp;[0x81, 0x80, 0x00, 0xc8, 0xe8, 0x56],
       to_bytes(&amp;[0x4000, 0x12_3456]).as_slice()
   );
   assert_eq!(
       &amp;[
           0xc0, 0x00, 0xc8, 0xe8, 0x56, 0xff, 0xff, 0xff, 0x7f, 0x00, 0xff, 0x7f, 0x81, 0x80,
           0x00,
       ],
       to_bytes(&amp;[0x2000, 0x12_3456, 0x0fff_ffff, 0x00, 0x3fff, 0x4000]).as_slice()
   );
}

#[test]
//#[ignore]
fn from_bytes_multiple_values() {
   assert_eq!(
       Ok(vec![0x2000, 0x12_3456, 0x0fff_ffff, 0x00, 0x3fff, 0x4000]),
       from_bytes(&amp;[
           0xc0, 0x00, 0xc8, 0xe8, 0x56, 0xff, 0xff, 0xff, 0x7f, 0x00, 0xff, 0x7f, 0x81, 0x80,
           0x00,
       ])
   );
}

#[test]
//#[ignore]
fn incomplete_byte_sequence() {
   assert_eq!(Err(Error::IncompleteNumber), from_bytes(&amp;[0xff]));
}

#[test]
//#[ignore]
fn zero_incomplete_byte_sequence() {
   assert_eq!(Err(Error::IncompleteNumber), from_bytes(&amp;[0x80]));
}

#[test]
//#[ignore]
fn overflow_u32() {
   assert_eq!(
       Err(Error::Overflow),
       from_bytes(&amp;[0xff, 0xff, 0xff, 0xff, 0x7f])
   );
}

#[test]
//#[ignore]
fn chained_execution_is_identity() {
   let test = &amp;[0xf2, 0xf6, 0x96, 0x9c, 0x3b, 0x39, 0x2e, 0x30, 0xb3, 0x24];
   assert_eq!(Ok(Vec::from(&amp;test[..])), from_bytes(&amp;to_bytes(test)));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-61" id="4-答案-61"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[derive(Debug, PartialEq)]
pub enum Error {
   IncompleteNumber,
   Overflow,
}

/// Convert a list of numbers to a stream of bytes encoded with variable length encoding.
pub fn to_bytes(values: &amp;[u32]) -&gt; Vec&lt;u8&gt; {
   let mut res = vec![];

   for value in values {
       res.append(&amp;mut to_bytes_single(*value));
   }
   res
}

fn to_bytes_single(mut value: u32) -&gt; Vec&lt;u8&gt; {
   // over allocates, but avoids growth
   let mut res = Vec::with_capacity(4);

   // 0 must be handled specially, because we need to push one byte
   if value == 0 {
       return vec![0];
   }

   while value &gt; 0 {
       // take the lower 7 bits
       let mut tmp = (value &amp; 0x7f) as u8;
       // remove them from the original value
       value &gt;&gt;= 7;

       // set continuation bit
       if !res.is_empty() {
           tmp |= 0x80;
       }

       res.push(tmp);
   }

   // order is wrong due to the way we pushed the data onto it
   res.reverse();
   res
}

// Alternative solution with hardcoded borders
// /// Convert a list of numbers to a stream of bytes encoded with variable length encoding.
// pub fn to_bytes(values: &amp;[u32]) -&gt; Vec&lt;u8&gt; {
//     let mut res = vec![];
//
//     for &amp;value in values {
//         if value &lt;= 0x7f {
//             res.push(value as u8);
//         } else if value &lt;= 0x3fff {
//             res.push(((value &gt;&gt; 7) &amp; 0xff) as u8 | 0x80);
//             res.push((value &amp; 0x7f) as u8);
//         } else if value &lt;= 0x1f_ffff {
//             res.push(((value &gt;&gt; 14) &amp; 0xff) as u8 | 0x80);
//             res.push(((value &gt;&gt; 7) &amp; 0xff) as u8 | 0x80);
//             res.push((value &amp; 0x7f) as u8);
//         } else if value &lt;= 0x0fff_ffff {
//             res.push(((value &gt;&gt; 21) &amp; 0xff) as u8 | 0x80);
//             res.push(((value &gt;&gt; 14) &amp; 0xff) as u8 | 0x80);
//             res.push(((value &gt;&gt; 7) &amp; 0xff) as u8 | 0x80);
//             res.push((value &amp; 0x7f) as u8);
//         } else {
//             res.push(((value &gt;&gt; 28) &amp; 0xff) as u8 | 0x80);
//             res.push(((value &gt;&gt; 21) &amp; 0xff) as u8 | 0x80);
//             res.push(((value &gt;&gt; 14) &amp; 0xff) as u8 | 0x80);
//             res.push(((value &gt;&gt; 7) &amp; 0xff) as u8 | 0x80);
//             res.push((value &amp; 0x7f) as u8);
//         }
//     }
//     res
// }

/// Given a stream of bytes, extract all numbers which are encoded in there.
pub fn from_bytes(bytes: &amp;[u8]) -&gt; Result&lt;Vec&lt;u32&gt;, Error&gt; {
   let mut res = vec![];
   let mut tmp = 0;
   for (i, b) in bytes.iter().enumerate() {
       // test if first 7 bit are set, to check for overflow
       if (tmp &amp; 0xfe_00_00_00) &gt; 0 {
           return Err(Error::Overflow);
       }

       // append bytes of b to tmp
       tmp = (tmp &lt;&lt; 7) | (b &amp; 0x7f) as u32;

       if 0x80 &amp; b == 0 {
           // continuation bit not set, number if complete
           res.push(tmp);
           tmp = 0;
       } else {
           // check for incomplete bytes
           if i + 1 == bytes.len() {
               // the next index would be past the end,
               // i.e. there are no more bytes.
               return Err(Error::IncompleteNumber);
           }
       }
   }

   Ok(res)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-61" id="填充相关-61"><h2>填充/相关</h2></a>
<a class="header" href="#phone-number" id="phone-number"><h1>Phone Number</h1></a>
<a class="header" href="#1-readme-62" id="1-readme-62"><h2>1. Readme</h2></a>
<a class="header" href="#电话号码" id="电话号码"><h1>电话号码</h1></a>
<p>整理用户输入的电话号码，以便他们可以发送短信.</p>
<p>这个**北美编号计划(NANP)**是北美洲、加拿大或百慕大群岛等许多国家使用的电话号码系统。所有 NANP 国家共享相同的国际国家代码:<code>1</code>。</p>
<p>NANP 数字是十位数字，由三位编号——区域划分代码组成，俗称<em>地区代码</em>其次是一个七位数的本地号码。本地号码的前三位数字表示<em>交换码</em>，剩余是唯一的四位数字，这是<em>用户号码</em>。</p>
<p>格式通常表示为</p>
<pre><code class="language-text">(NXX)-NXX-XXXX
</code></pre>
<p>这里的<code>N</code>是从 2 到 9 的任何数字，而<code>X</code>是从 0 到 9 的任何数字.</p>
<p>您的任务是通过删除标点符号和国家代码(1)，整理不同格式的电话号码。</p>
<p>例如，输入</p>
<ul>
<li><code>+1 (613)-995-0253</code></li>
<li><code>613-995-0253</code></li>
<li><code>1 613 995 0253</code></li>
<li><code>613.995.0253</code></li>
</ul>
<p>都应该产出</p>
<p><code>6139950253</code></p>
<p>**注:**因为这个练习只涉及 NANP 国家使用的电话号码，只有 1 被认为是有效的国家代码。</p>
<a class="header" href="#资源-49" id="资源-49"><h2>资源</h2></a>
<p>JumpstartLab 的事件管理器<a href="http://tutorials.jumpstartlab.com/projects/eventmanager.html">http://tutorials.jumpstartlab.com/projects/eventmanager.html</a></p>
<a class="header" href="#2-开始你的表演-62" id="2-开始你的表演-62"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn number(user_number: &amp;str) -&gt; Option&lt;String&gt; {
   unimplemented!(
       &quot;Given the number entered by user '{}', convert it into SMS-friendly format. If the entered number is not a valid NANP number, return None.&quot;,
       user_number
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-62" id="3-测试代码查看-62"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn to_some_string(s: &amp;str) -&gt; Option&lt;String&gt; {
   Some(s.to_string())
}

#[test]
fn test_cleans_the_number() {
   assert_eq!(number(&quot;(223) 456-7890&quot;), to_some_string(&quot;2234567890&quot;));
}

#[test]
//#[ignore]
fn test_cleans_numbers_with_dots() {
   assert_eq!(number(&quot;223.456.7890&quot;), to_some_string(&quot;2234567890&quot;));
}

#[test]
//#[ignore]
fn test_cleans_numbers_with_multiple_spaces() {
   assert_eq!(number(&quot;223 456   7890   &quot;), to_some_string(&quot;2234567890&quot;));
}

#[test]
//#[ignore]
fn test_invalid_when_9_digits() {
   assert_eq!(number(&quot;123456789&quot;), None);
}

#[test]
//#[ignore]
fn test_invalid_when_11_digits_does_not_start_with_a_1() {
   assert_eq!(number(&quot;22234567890&quot;), None);
}

#[test]
//#[ignore]
fn test_valid_when_11_digits_and_starting_with_1() {
   assert_eq!(number(&quot;12234567890&quot;), to_some_string(&quot;2234567890&quot;));
}

#[test]
//#[ignore]
fn test_valid_when_11_digits_and_starting_with_1_even_with_punctuation() {
   assert_eq!(number(&quot;+1 (223) 456-7890&quot;), to_some_string(&quot;2234567890&quot;));
}

#[test]
//#[ignore]
fn test_invalid_when_more_than_11_digits() {
   assert_eq!(number(&quot;321234567890&quot;), None);
}

#[test]
//#[ignore]
fn test_invalid_with_letters() {
   assert_eq!(number(&quot;123-abc-7890&quot;), None);
}

#[test]
//#[ignore]
fn test_invalid_with_punctuations() {
   assert_eq!(number(&quot;123-@:!-7890&quot;), None);
}

#[test]
//#[ignore]
fn test_invalid_if_area_code_does_not_start_with_2_9() {
   assert_eq!(number(&quot;(123) 456-7890&quot;), None);
}

#[test]
//#[ignore]
fn test_invalid_if_exchange_code_does_not_start_with_2_9() {
   assert_eq!(number(&quot;(223) 056-7890&quot;), None);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-62" id="4-答案-62"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn number(s: &amp;str) -&gt; Option&lt;String&gt; {
   let digits: String = s.chars().filter(|&amp;c| c.is_digit(10)).collect();
   match digits.len() {
       10 =&gt; match (digits.chars().nth(0), digits.chars().nth(3)) {
           (Some('0'), _) =&gt; None,
           (Some('1'), _) =&gt; None,
           (_, Some('0')) =&gt; None,
           (_, Some('1')) =&gt; None,
           _ =&gt; Some(digits),
       },
       11 =&gt; match digits.chars().nth(0) {
           Some('1') =&gt; Some(digits[1..].to_string()),
           _ =&gt; None,
       },
       _ =&gt; None,
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-62" id="填充相关-62"><h2>填充/相关</h2></a>
<a class="header" href="#wordy" id="wordy"><h1>Wordy</h1></a>
<a class="header" href="#1-readme-63" id="1-readme-63"><h2>1. Readme</h2></a>
<a class="header" href="#罗唆" id="罗唆"><h1>罗唆</h1></a>
<p>解析并运算简单的数学单词问题，将答案作为整数返回。</p>
<a class="header" href="#迭代-1---加法" id="迭代-1---加法"><h2>迭代 1 - 加法</h2></a>
<p>将两个数字相加</p>
<blockquote>
<p>What is 5 plus 13?</p>
</blockquote>
<p>运算为 18.</p>
<p>处理大数和负数。</p>
<a class="header" href="#迭代-2---减法乘法和除法" id="迭代-2---减法乘法和除法"><h2>迭代 2 - 减法，乘法和除法</h2></a>
<p>现在，执行其他三个操作.</p>
<blockquote>
<p>What is 7 minus 5?</p>
</blockquote>
<p>2</p>
<blockquote>
<p>What is 6 multiplied by 4?</p>
</blockquote>
<p>24</p>
<blockquote>
<p>What is 25 divided by 5?</p>
</blockquote>
<p>五</p>
<a class="header" href="#迭代-3---多个操作" id="迭代-3---多个操作"><h2>迭代 3 - 多个操作</h2></a>
<p>按顺序处理一组操作.</p>
<p>由于这些是口头语言问题，从左到右运算表达式，<em>忽略了典型的操作顺序(乘法优先级比加法高)。</em></p>
<blockquote>
<p>What is 5 plus 13 plus 6?</p>
</blockquote>
<p>24</p>
<blockquote>
<p>What is 3 plus 2 multiplied by 3?</p>
</blockquote>
<p>15(不是 9)</p>
<a class="header" href="#奖金---指数" id="奖金---指数"><h2>奖金 - 指数</h2></a>
<p>如果你愿意，处理指数.</p>
<blockquote>
<p>What is 2 raised to the 5th power?</p>
</blockquote>
<p>32</p>
<a class="header" href="#资源-50" id="资源-50"><h2>资源</h2></a>
<p>灵感来自 Extreme Startup 游戏中的一个生成的问题.<a href="https://github.com/rchatley/extreme_startup">https://github.com/rchatley/extreme_startup</a></p>
<a class="header" href="#2-开始你的表演-63" id="2-开始你的表演-63"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub struct WordProblem;

pub fn answer(command: &amp;str) -&gt; Option&lt;i32&gt; {
   unimplemented!(
       &quot;Return the result of the command '{}' or None, if the command is invalid.&quot;,
       command
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-63" id="3-测试代码查看-63"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn addition() {
   let command = &quot;What is 1 plus 1?&quot;;
   assert_eq!(Some(2), answer(command));
}

#[test]
//#[ignore]
fn more_addition() {
   let command = &quot;What is 53 plus 2?&quot;;
   assert_eq!(Some(55), answer(command));
}

#[test]
//#[ignore]
fn addition_with_negative_numbers() {
   let command = &quot;What is -1 plus -10?&quot;;
   assert_eq!(Some(-11), answer(command));
}

#[test]
//#[ignore]
fn large_addition() {
   let command = &quot;What is 123 plus 45678?&quot;;
   assert_eq!(Some(45801), answer(command));
}

#[test]
//#[ignore]
fn subtraction() {
   let command = &quot;What is 4 minus -12?&quot;;
   assert_eq!(Some(16), answer(command));
}

#[test]
//#[ignore]
fn multiplication() {
   let command = &quot;What is -3 multiplied by 25?&quot;;
   assert_eq!(Some(-75), answer(command));
}

#[test]
//#[ignore]
fn division() {
   let command = &quot;What is 33 divided by -3?&quot;;
   assert_eq!(Some(-11), answer(command));
}

#[test]
//#[ignore]
fn multiple_additions() {
   let command = &quot;What is 1 plus 1 plus 1?&quot;;
   assert_eq!(Some(3), answer(command));
}

#[test]
//#[ignore]
fn addition_and_subtraction() {
   let command = &quot;What is 1 plus 5 minus -2?&quot;;
   assert_eq!(Some(8), answer(command));
}

#[test]
//#[ignore]
fn multiple_subtraction() {
   let command = &quot;What is 20 minus 4 minus 13?&quot;;
   assert_eq!(Some(3), answer(command));
}

#[test]
//#[ignore]
fn subtraction_then_addition() {
   let command = &quot;What is 17 minus 6 plus 3?&quot;;
   assert_eq!(Some(14), answer(command));
}

#[test]
//#[ignore]
fn multiple_multiplications() {
   let command = &quot;What is 2 multiplied by -2 multiplied by 3?&quot;;
   assert_eq!(Some(-12), answer(command));
}

#[test]
//#[ignore]
fn addition_and_multiplication() {
   let command = &quot;What is -3 plus 7 multiplied by -2?&quot;;
   assert_eq!(Some(-8), answer(command));
}

#[test]
//#[ignore]
fn multiple_divisions() {
   let command = &quot;What is -12 divided by 2 divided by -3?&quot;;
   assert_eq!(Some(2), answer(command));
}

#[test]
//#[ignore]
fn unknown_operation() {
   let command = &quot;What is 52 cubed?&quot;;
   assert!(answer(command).is_none());
}

#[test]
//#[ignore]
fn non_math_question() {
   let command = &quot;Who is the President of the United States?&quot;;
   assert!(answer(command).is_none());
}

#}</code></pre></pre>
<a class="header" href="#4-答案-63" id="4-答案-63"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
struct Token&lt;'a&gt; {
   value: &amp;'a str,
}

impl &lt;'a&gt; Token&lt;'a&gt; {
   fn is_valid(&amp;self) -&gt; bool {
       !self.value.is_empty() &amp;&amp; (self.is_operand() || self.is_operator())
   }

   fn is_operand(&amp;self) -&gt; bool {
       self.value.chars().all(|c| c.is_numeric() || c == '-')
   }

   fn is_operator(&amp;self) -&gt; bool {
       self.value == &quot;plus&quot;
           || self.value == &quot;minus&quot;
           || self.value == &quot;multiplied&quot;
           || self.value == &quot;divided&quot;
   }
}

pub fn answer(c: &amp;str) -&gt; Option&lt;i32&gt; {
   let mut t = tokens(c);
   let mut result: i32 = 0;
   let mut opr = &quot;plus&quot;;

   if t.len() &lt;= 1 {
       None
   } else {
       while t.len() &gt; 1 {
           result = evaluate(result, opr, operand(&amp;t.remove(0)));
           opr = operator(&amp;t.remove(0));
       }
       result = evaluate(result, opr, operand(&amp;t.remove(0)));
       Some(result)
   }
}

fn evaluate(r: i32, operator: &amp;str, operand: i32) -&gt; i32 {
   match operator {
       &quot;plus&quot; =&gt; r + operand,
       &quot;minus&quot; =&gt; r - operand,
       &quot;multiplied&quot; =&gt; r * operand,
       &quot;divided&quot; =&gt; r / operand,
       _ =&gt; r,
   }
}

fn operand(t: &amp;Token) -&gt; i32 {
   t.value.parse().unwrap()
}

fn operator&lt;'a&gt;(t: &amp;Token&lt;'a&gt;) -&gt; &amp;'a str {
   t.value
}

fn tokens&lt;'a&gt;(command: &amp;'a str) -&gt; Vec&lt;Token&lt;'a&gt;&gt; {
   command
       .split(|c: char| c.is_whitespace() || c == '?')
       .map(|w| Token {
           value: w,
       })
       .filter(|t| t.is_valid())
       .collect()
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-63" id="填充相关-63"><h2>填充/相关</h2></a>
<a class="header" href="#tournament" id="tournament"><h1>Tournament</h1></a>
<a class="header" href="#1-readme-64" id="1-readme-64"><h2>1. Readme</h2></a>
<a class="header" href="#锦标赛" id="锦标赛"><h1>锦标赛</h1></a>
<p>统计一场小型足球比赛的结果.</p>
<p>基于一个输入文件，它包含哪个队与哪个队进行比赛，结果是什么。用下面的表格创建出一个文件:</p>
<pre><code class="language-text">Team                           | MP |  W |  D |  L |  P
Devastating Donkeys            |  3 |  2 |  1 |  0 |  7
Allegoric Alaskans             |  3 |  2 |  0 |  1 |  6
Blithering Badgers             |  3 |  1 |  0 |  2 |  3
Courageous Californians        |  3 |  0 |  1 |  2 |  1
</code></pre>
<p>那些缩写是什么意思?</p>
<ul>
<li>MP：赛次</li>
<li>W：比赛赢了</li>
<li>D：打平</li>
<li>L：比赛输了</li>
<li>P：分</li>
</ul>
<p>一场胜利，3 分。打平 1 分。输了 0 分.</p>
<p>结果应该按分数下降排序。在平局的情况下，球队按字母顺序排列。</p>
<a class="header" href="#输入" id="输入"><h3>输入</h3></a>
<p>你的梳理程序，将接收像这样的输入:</p>
<pre><code class="language-text">Allegoric Alaskans;Blithering Badgers;win
Devastating Donkeys;Courageous Californians;draw
Devastating Donkeys;Allegoric Alaskans;win
Courageous Californians;Blithering Badgers;loss
Blithering Badgers;Devastating Donkeys;loss
Allegoric Alaskans;Courageous Californians;win
</code></pre>
<p>一行中首个队伍名是主队。所以这一行</p>
<pre><code class="language-text">Allegoric Alaskans;Blithering Badgers;win
</code></pre>
<p>意味着，Allegoric Alaskans 打败了 Blithering Badgers。</p>
<p>这行:</p>
<pre><code class="language-text">Courageous Californians;Blithering Badgers;loss
</code></pre>
<p>意味着，Courageous Californians 输给了 Blithering Badgers</p>
<p>这行:</p>
<pre><code class="language-text">Devastating Donkeys;Courageous Californians;draw
</code></pre>
<p>意味着，Devastating Donkeys 与 Courageous Californians 打平</p>
<a class="header" href="#2-开始你的表演-64" id="2-开始你的表演-64"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn tally(match_results: &amp;str) -&gt; String {
   unimplemented!(
       &quot;Given the result of the played matches '{}' return a properly formatted tally table string.&quot;,
       match_results
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-64" id="3-测试代码查看-64"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn just_the_header_if_no_input() {
   let input = &quot;&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#[test]
//#[ignore]
fn a_win_is_three_points_a_loss_is_zero_points() {
   let input = &quot;Allegoric Alaskans;Blithering Badgers;win&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P\n&quot;.to_string()
       + &quot;Allegoric Alaskans             |  1 |  1 |  0 |  0 |  3\n&quot;
       + &quot;Blithering Badgers             |  1 |  0 |  0 |  1 |  0&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#[test]
//#[ignore]
fn a_win_can_also_be_expressed_as_a_loss() {
   let input = &quot;Blithering Badgers;Allegoric Alaskans;loss&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P\n&quot;.to_string()
       + &quot;Allegoric Alaskans             |  1 |  1 |  0 |  0 |  3\n&quot;
       + &quot;Blithering Badgers             |  1 |  0 |  0 |  1 |  0&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#[test]
//#[ignore]
fn a_different_team_can_win() {
   let input = &quot;Blithering Badgers;Allegoric Alaskans;win&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P\n&quot;.to_string()
       + &quot;Blithering Badgers             |  1 |  1 |  0 |  0 |  3\n&quot;
       + &quot;Allegoric Alaskans             |  1 |  0 |  0 |  1 |  0&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#[test]
//#[ignore]
fn a_draw_is_one_point_each() {
   let input = &quot;Allegoric Alaskans;Blithering Badgers;draw&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P\n&quot;.to_string()
       + &quot;Allegoric Alaskans             |  1 |  0 |  1 |  0 |  1\n&quot;
       + &quot;Blithering Badgers             |  1 |  0 |  1 |  0 |  1&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#[test]
//#[ignore]
fn there_can_be_more_than_one_match() {
   let input = &quot;Allegoric Alaskans;Blithering Badgers;win\n&quot;.to_string()
       + &quot;Allegoric Alaskans;Blithering Badgers;win&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P\n&quot;.to_string()
       + &quot;Allegoric Alaskans             |  2 |  2 |  0 |  0 |  6\n&quot;
       + &quot;Blithering Badgers             |  2 |  0 |  0 |  2 |  0&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#[test]
//#[ignore]
fn there_can_be_more_than_one_winner() {
   let input = &quot;Allegoric Alaskans;Blithering Badgers;loss\n&quot;.to_string()
       + &quot;Allegoric Alaskans;Blithering Badgers;win&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P\n&quot;.to_string()
       + &quot;Allegoric Alaskans             |  2 |  1 |  0 |  1 |  3\n&quot;
       + &quot;Blithering Badgers             |  2 |  1 |  0 |  1 |  3&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#[test]
//#[ignore]
fn there_can_be_more_than_two_teams() {
   let input = &quot;Allegoric Alaskans;Blithering Badgers;win\n&quot;.to_string()
       + &quot;Blithering Badgers;Courageous Californians;win\n&quot;
       + &quot;Courageous Californians;Allegoric Alaskans;loss&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P\n&quot;.to_string()
       + &quot;Allegoric Alaskans             |  2 |  2 |  0 |  0 |  6\n&quot;
       + &quot;Blithering Badgers             |  2 |  1 |  0 |  1 |  3\n&quot;
       + &quot;Courageous Californians        |  2 |  0 |  0 |  2 |  0&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#[test]
//#[ignore]
fn typical_input() {
   let input = &quot;Allegoric Alaskans;Blithering Badgers;win\n&quot;.to_string()
       + &quot;Devastating Donkeys;Courageous Californians;draw\n&quot;
       + &quot;Devastating Donkeys;Allegoric Alaskans;win\n&quot;
       + &quot;Courageous Californians;Blithering Badgers;loss\n&quot;
       + &quot;Blithering Badgers;Devastating Donkeys;loss\n&quot;
       + &quot;Allegoric Alaskans;Courageous Californians;win&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P\n&quot;.to_string()
       + &quot;Devastating Donkeys            |  3 |  2 |  1 |  0 |  7\n&quot;
       + &quot;Allegoric Alaskans             |  3 |  2 |  0 |  1 |  6\n&quot;
       + &quot;Blithering Badgers             |  3 |  1 |  0 |  2 |  3\n&quot;
       + &quot;Courageous Californians        |  3 |  0 |  1 |  2 |  1&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#[test]
//#[ignore]
fn incomplete_competition_not_all_pairs_have_played() {
   let input = &quot;Allegoric Alaskans;Blithering Badgers;loss\n&quot;.to_string()
       + &quot;Devastating Donkeys;Allegoric Alaskans;loss\n&quot;
       + &quot;Courageous Californians;Blithering Badgers;draw\n&quot;
       + &quot;Allegoric Alaskans;Courageous Californians;win&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P\n&quot;.to_string()
       + &quot;Allegoric Alaskans             |  3 |  2 |  0 |  1 |  6\n&quot;
       + &quot;Blithering Badgers             |  2 |  1 |  1 |  0 |  4\n&quot;
       + &quot;Courageous Californians        |  2 |  0 |  1 |  1 |  1\n&quot;
       + &quot;Devastating Donkeys            |  1 |  0 |  0 |  1 |  0&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#[test]
//#[ignore]
fn ties_broken_alphabetically() {
   let input = &quot;Courageous Californians;Devastating Donkeys;win\n&quot;.to_string()
       + &quot;Allegoric Alaskans;Blithering Badgers;win\n&quot;
       + &quot;Devastating Donkeys;Allegoric Alaskans;loss\n&quot;
       + &quot;Courageous Californians;Blithering Badgers;win\n&quot;
       + &quot;Blithering Badgers;Devastating Donkeys;draw\n&quot;
       + &quot;Allegoric Alaskans;Courageous Californians;draw&quot;;
   let expected = &quot;Team                           | MP |  W |  D |  L |  P\n&quot;.to_string()
       + &quot;Allegoric Alaskans             |  3 |  2 |  1 |  0 |  7\n&quot;
       + &quot;Courageous Californians        |  3 |  2 |  1 |  0 |  7\n&quot;
       + &quot;Blithering Badgers             |  3 |  0 |  1 |  2 |  1\n&quot;
       + &quot;Devastating Donkeys            |  3 |  0 |  1 |  2 |  1&quot;;

   assert_eq!(tally(&amp;input), expected);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-64" id="4-答案-64"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::cmp::Ordering::Equal;
use std::collections::HashMap;

enum GameResult {
   Win,
   Draw,
   Loss,
}

struct TeamResult {
   wins: u32,
   draws: u32,
   losses: u32,
}

impl TeamResult {
   fn new() -&gt; TeamResult {
       TeamResult {
           wins: 0,
           draws: 0,
           losses: 0,
       }
   }
   fn add_game_result(&amp;mut self, result: GameResult) {
       match result {
           GameResult::Win =&gt; self.wins += 1,
           GameResult::Draw =&gt; self.draws += 1,
           GameResult::Loss =&gt; self.losses += 1,
       }
   }
}

pub fn tally(input: &amp;str) -&gt; String {
   let mut results: HashMap&lt;String, TeamResult&gt; = HashMap::new();
   for line in input.to_string().lines() {
       let parts: Vec&lt;&amp;str&gt; = line.trim_right().split(';').collect();
       if parts.len() != 3 {
           continue;
       }
       let team1 = parts[0];
       let team2 = parts[1];
       let outcome = parts[2];
       match outcome {
           &quot;win&quot; =&gt; {
               add_game_result(&amp;mut results, team1.to_string(), GameResult::Win);
               add_game_result(&amp;mut results, team2.to_string(), GameResult::Loss);
           }
           &quot;draw&quot; =&gt; {
               add_game_result(&amp;mut results, team1.to_string(), GameResult::Draw);
               add_game_result(&amp;mut results, team2.to_string(), GameResult::Draw);
           }
           &quot;loss&quot; =&gt; {
               add_game_result(&amp;mut results, team1.to_string(), GameResult::Loss);
               add_game_result(&amp;mut results, team2.to_string(), GameResult::Win);
           }
           _ =&gt; (), // Ignore bad lines
       }
   }
   write_tally(&amp;results)
}

fn write_tally(results: &amp;HashMap&lt;String, TeamResult&gt;) -&gt; String {
   let mut v: Vec&lt;_&gt; = results
       .iter()
       .map(|(team, r)| {
           let games = r.wins + r.draws + r.losses;
           let points = r.wins * 3 + r.draws;
           (team, games, r, points)
       })
       .collect();
   // Sort by points descending, then name A-Z.
   v.sort_by(|a, b| match a.3.cmp(&amp;(b.3)).reverse() {
       Equal =&gt; a.0.cmp(&amp;(b.0)),
       other =&gt; other,
   });
   let mut lines = vec![format!(&quot;{:30} | MP |  W |  D |  L |  P&quot;, &quot;Team&quot;)];
   lines.extend(v.iter().map(|&amp;(ref team, games, r, points)| {
       format!(
           &quot;{:30} | {:2} | {:2} | {:2} | {:2} | {:2}&quot;,
           team, games, r.wins, r.draws, r.losses, points
       )
   }));
   lines.join(&quot;\n&quot;)
}

fn add_game_result(results: &amp;mut HashMap&lt;String, TeamResult&gt;, team: String, result: GameResult) {
   results
       .entry(team)
       .or_insert(TeamResult::new())
       .add_game_result(result);
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-64" id="填充相关-64"><h2>填充/相关</h2></a>
<a class="header" href="#custom-set" id="custom-set"><h1>Custom Set</h1></a>
<a class="header" href="#1-readme-65" id="1-readme-65"><h2>1. Readme</h2></a>
<a class="header" href="#自定义集合" id="自定义集合"><h1>自定义集合</h1></a>
<p>创建自定义 set 类型。</p>
<p>有时需要定义某种类型的自定义数据结构，例如一个集合(set)。在本练习中，您将定义自己的集合。它的内部工作原理无关紧要，只要它的行为就像一组唯一元素的集合。</p>
<a class="header" href="#2-开始你的表演-65" id="2-开始你的表演-65"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::fmt::Debug;
use std::marker::PhantomData;

#[derive(Debug, PartialEq)]
pub struct CustomSet&lt;T&gt; {
   // This field is here to make the template compile and not to
   // complain about unused type parameter 'T'. Once you start
   // solving the exercise, delete this field and the 'std::marker::PhantomData'
   // import.
   phantom: PhantomData&lt;T&gt;,
}

impl&lt;T: Debug&gt; CustomSet&lt;T&gt; {
   pub fn new(input: &amp;[T]) -&gt; Self {
       unimplemented!(
           &quot;From the given input '{:?}' construct a new CustomSet struct.&quot;,
           input
       );
   }

   pub fn contains(&amp;self, element: &amp;T) -&gt; bool {
       unimplemented!(
           &quot;Determine if the '{:?}' element is present in the CustomSet struct.&quot;,
           element
       );
   }

   pub fn add(&amp;mut self, element: T) {
       unimplemented!(&quot;Add the '{:?}' element to the CustomSet struct.&quot;, element);
   }

   pub fn is_subset(&amp;self, other: &amp;Self) -&gt; bool {
       unimplemented!(
           &quot;Determine if the CustomSet struct is a subset of the other '{:?}' struct.&quot;,
           other
       );
   }

   pub fn is_empty(&amp;self) -&gt; bool {
       unimplemented!(&quot;Determine if the CustomSet struct is empty.&quot;);
   }

   pub fn is_disjoint(&amp;self, other: &amp;Self) -&gt; bool {
       unimplemented!(
           &quot;Determine if the CustomSet struct and the other struct '{:?}' are disjoint.&quot;,
           other
       );
   }

   pub fn intersection(&amp;self, other: &amp;Self) -&gt; Self {
       unimplemented!(&quot;Construct a new CustomSet struct that is an intersection between current struct and the other struct '{:?}'.&quot;, other);
   }

   pub fn difference(&amp;self, other: &amp;Self) -&gt; Self {
       unimplemented!(&quot;Construct a new CustomSet struct that is a difference between current struct and the other struct '{:?}'.&quot;, other);
   }

   pub fn union(&amp;self, other: &amp;Self) -&gt; Self {
       unimplemented!(&quot;Construct a new CustomSet struct that is an union between current struct and the other struct '{:?}'.&quot;, other);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-65" id="3-测试代码查看-65"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn sets_with_no_elements_are_empty() {
   let set: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   assert!(set.is_empty());
}

#[test]
//#[ignore]
fn sets_with_elements_are_not_empty() {
   let set = CustomSet::new(&amp;[1]);
   assert!(!set.is_empty());
}

#[test]
//#[ignore]
fn nothing_is_contained_in_an_empty_set() {
   let set = CustomSet::new(&amp;[]);
   assert!(!set.contains(&amp;1));
}

#[test]
//#[ignore]
fn true_when_the_element_is_in_the_set() {
   let set = CustomSet::new(&amp;[1, 2, 3]);
   assert!(set.contains(&amp;1));
}

#[test]
//#[ignore]
fn false_when_the_element_is_not_in_the_set() {
   let set = CustomSet::new(&amp;[1, 2, 3]);
   assert!(!set.contains(&amp;4));
}

#[test]
//#[ignore]
fn empty_sets_are_subsets_of_each_other() {
   let set1: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   let set2: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   assert!(set1.is_subset(&amp;set2));
   assert!(set2.is_subset(&amp;set1));
}

#[test]
//#[ignore]
fn empty_set_is_subset_of_non_empty_set() {
   let set1 = CustomSet::new(&amp;[]);
   let set2 = CustomSet::new(&amp;[1]);
   assert!(set1.is_subset(&amp;set2));
}

#[test]
//#[ignore]
fn non_empty_set_is_not_subset_of_empty_set() {
   let set1 = CustomSet::new(&amp;[1]);
   let set2 = CustomSet::new(&amp;[]);
   assert!(!set1.is_subset(&amp;set2));
}

#[test]
//#[ignore]
fn sets_with_same_elements_are_subsets() {
   let set1 = CustomSet::new(&amp;[1, 2, 3]);
   let set2 = CustomSet::new(&amp;[1, 2, 3]);
   assert!(set1.is_subset(&amp;set2));
   assert!(set2.is_subset(&amp;set1));
}

#[test]
//#[ignore]
fn set_contained_in_other_set_is_a_subset() {
   let set1 = CustomSet::new(&amp;[1, 2, 3]);
   let set2 = CustomSet::new(&amp;[4, 1, 2, 3]);
   assert!(set1.is_subset(&amp;set2));
}

#[test]
//#[ignore]
fn set_not_contained_in_other_set_is_not_a_subset_one() {
   let set1 = CustomSet::new(&amp;[1, 2, 3]);
   let set2 = CustomSet::new(&amp;[4, 1, 3]);
   assert!(!set1.is_subset(&amp;set2));
}

#[test]
//#[ignore]
fn empty_sets_are_disjoint_with_each_other() {
   let set1: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   let set2: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   assert!(set1.is_disjoint(&amp;set2));
   assert!(set2.is_disjoint(&amp;set1));
}

#[test]
//#[ignore]
fn empty_set_disjoint_with_non_empty_set() {
   let set1 = CustomSet::new(&amp;[]);
   let set2 = CustomSet::new(&amp;[1]);
   assert!(set1.is_disjoint(&amp;set2));
}

#[test]
//#[ignore]
fn non_empty_set_disjoint_with_empty_set() {
   let set1 = CustomSet::new(&amp;[1]);
   let set2 = CustomSet::new(&amp;[]);
   assert!(set1.is_disjoint(&amp;set2));
}

#[test]
//#[ignore]
fn sets_with_one_element_in_common_are_not_disjoint() {
   let set1 = CustomSet::new(&amp;[1, 2]);
   let set2 = CustomSet::new(&amp;[2, 3]);
   assert!(!set1.is_disjoint(&amp;set2));
   assert!(!set2.is_disjoint(&amp;set1));
}

#[test]
//#[ignore]
fn sets_with_no_elements_in_common_are_disjoint() {
   let set1 = CustomSet::new(&amp;[1, 2]);
   let set2 = CustomSet::new(&amp;[3, 4]);
   assert!(set1.is_disjoint(&amp;set2));
   assert!(set2.is_disjoint(&amp;set1));
}

#[test]
//#[ignore]
fn empty_sets_are_equal() {
   let set1: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   let set2: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   assert_eq!(set1, set2);
}

#[test]
//#[ignore]
fn empty_set_is_not_equal_to_a_non_empty_set() {
   let set1 = CustomSet::new(&amp;[]);
   let set2 = CustomSet::new(&amp;[1, 2, 3]);
   assert_ne!(set1, set2);
}

#[test]
//#[ignore]
fn non_empty_set_is_not_equal_to_an_empty_set() {
   let set1 = CustomSet::new(&amp;[1, 2, 3]);
   let set2 = CustomSet::new(&amp;[]);
   assert_ne!(set1, set2);
}

#[test]
//#[ignore]
fn sets_with_the_same_elements_are_equal() {
   let set1 = CustomSet::new(&amp;[1, 2]);
   let set2 = CustomSet::new(&amp;[2, 1]);
   assert_eq!(set1, set2);
}

#[test]
//#[ignore]
fn sets_with_different_elements_are_not_equal() {
   let set1 = CustomSet::new(&amp;[1, 2, 3]);
   let set2 = CustomSet::new(&amp;[2, 1, 4]);
   assert_ne!(set1, set2);
}

#[test]
//#[ignore]
fn add_to_empty_set() {
   let mut set = CustomSet::new(&amp;[]);
   set.add(3);
   assert_eq!(set, CustomSet::new(&amp;[3]));
}

#[test]
//#[ignore]
fn add_to_non_empty_set() {
   let mut set = CustomSet::new(&amp;[1, 2, 4]);
   set.add(3);
   assert_eq!(set, CustomSet::new(&amp;[1, 2, 3, 4]));
}

#[test]
//#[ignore]
fn add_existing_element() {
   let mut set = CustomSet::new(&amp;[1, 2, 3]);
   set.add(3);
   assert_eq!(set, CustomSet::new(&amp;[1, 2, 3]));
}

#[test]
//#[ignore]
fn intersecting_empty_sets_return_empty_set() {
   let set1: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   let set2: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   assert_eq!(set1.intersection(&amp;set2), CustomSet::new(&amp;[]));
}

#[test]
//#[ignore]
fn intersecting_empty_set_with_non_empty_returns_empty_set() {
   let set1 = CustomSet::new(&amp;[]);
   let set2 = CustomSet::new(&amp;[3, 2, 5]);
   assert_eq!(set1.intersection(&amp;set2), CustomSet::new(&amp;[]));
}

#[test]
//#[ignore]
fn intersecting_non_empty_set_with_empty_returns_empty_set() {
   let set1 = CustomSet::new(&amp;[1, 2, 3, 4]);
   let set2 = CustomSet::new(&amp;[]);
   assert_eq!(set1.intersection(&amp;set2), CustomSet::new(&amp;[]));
}

#[test]
//#[ignore]
fn intersection_of_two_sets_with_no_shared_elements_is_an_empty_set() {
   let set1 = CustomSet::new(&amp;[1, 2, 3]);
   let set2 = CustomSet::new(&amp;[4, 5, 6]);
   assert_eq!(set1.intersection(&amp;set2), CustomSet::new(&amp;[]));
   assert_eq!(set2.intersection(&amp;set1), CustomSet::new(&amp;[]));
}

#[test]
//#[ignore]
fn intersection_of_two_sets_with_shared_elements_is_a_set_of_the_shared_elements() {
   let set1 = CustomSet::new(&amp;[1, 2, 3, 4]);
   let set2 = CustomSet::new(&amp;[3, 2, 5]);
   assert_eq!(set1.intersection(&amp;set2), CustomSet::new(&amp;[2, 3]));
   assert_eq!(set2.intersection(&amp;set1), CustomSet::new(&amp;[2, 3]));
}

#[test]
//#[ignore]
fn difference_of_two_empty_sets_is_empty_set() {
   let set1: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   let set2: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   assert_eq!(set1.difference(&amp;set2), CustomSet::new(&amp;[]));
}

#[test]
//#[ignore]
fn difference_of_an_empty_and_non_empty_set_is_an_empty_set() {
   let set1 = CustomSet::new(&amp;[]);
   let set2 = CustomSet::new(&amp;[3, 2, 5]);
   assert_eq!(set1.difference(&amp;set2), CustomSet::new(&amp;[]));
}

#[test]
//#[ignore]
fn difference_of_a_non_empty_set_and_empty_set_is_the_non_empty_set() {
   let set1 = CustomSet::new(&amp;[1, 2, 3, 4]);
   let set2 = CustomSet::new(&amp;[]);
   assert_eq!(set1.difference(&amp;set2), CustomSet::new(&amp;[1, 2, 3, 4]));
}

#[test]
//#[ignore]
fn difference_of_two_non_empty_sets_is_elements_only_in_first_set_one() {
   let set1 = CustomSet::new(&amp;[3, 2, 1]);
   let set2 = CustomSet::new(&amp;[2, 4]);
   assert_eq!(set1.difference(&amp;set2), CustomSet::new(&amp;[1, 3]));
}

#[test]
//#[ignore]
fn union_of_two_empty_sets_is_empty_set() {
   let set1: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   let set2: CustomSet&lt;()&gt; = CustomSet::new(&amp;[]);
   assert_eq!(set1.union(&amp;set2), CustomSet::new(&amp;[]));
}

#[test]
//#[ignore]
fn union_of_empty_set_and_non_empty_set_is_all_elements() {
   let set1 = CustomSet::new(&amp;[]);
   let set2 = CustomSet::new(&amp;[2]);
   assert_eq!(set1.union(&amp;set2), CustomSet::new(&amp;[2]));
}

#[test]
//#[ignore]
fn union_of_non_empty_set_and_empty_set_is_the_non_empty_set() {
   let set1 = CustomSet::new(&amp;[1, 3]);
   let set2 = CustomSet::new(&amp;[]);
   assert_eq!(set1.union(&amp;set2), CustomSet::new(&amp;[1, 3]));
}

#[test]
//#[ignore]
fn union_of_non_empty_sets_contains_all_unique_elements() {
   let set1 = CustomSet::new(&amp;[1, 3]);
   let set2 = CustomSet::new(&amp;[2, 3]);
   assert_eq!(set1.union(&amp;set2), CustomSet::new(&amp;[3, 2, 1]));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-65" id="4-答案-65"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[derive(Debug)]
pub struct CustomSet&lt;T&gt; {
   collection: Vec&lt;T&gt;,
}

impl&lt;T: Ord + Clone&gt; PartialEq for CustomSet&lt;T&gt; {
   fn eq(&amp;self, other: &amp;Self) -&gt; bool {
       self.collection.iter().all(|x| other.contains(&amp;x))
           &amp;&amp; other.collection.iter().all(|x| self.contains(&amp;x))
   }
}

impl&lt;T: Ord + Clone&gt; CustomSet&lt;T&gt; {
   pub fn new(inputs: &amp;[T]) -&gt; CustomSet&lt;T&gt; {
       let mut s = CustomSet {
           collection: Vec::new(),
       };
       for input in inputs {
           s.add(input.clone());
       }
       s
   }

   pub fn add(&amp;mut self, element: T) {
       if !self.contains(&amp;element) {
           self.collection.push(element)
       }
   }

   pub fn contains(&amp;self, other: &amp;T) -&gt; bool {
       self.collection.contains(other)
   }

   pub fn is_empty(&amp;self) -&gt; bool {
       self.collection.is_empty()
   }

   pub fn is_subset(&amp;self, other: &amp;Self) -&gt; bool {
       self.collection.iter().all(|x| other.contains(x))
   }

   pub fn is_disjoint(&amp;self, other: &amp;Self) -&gt; bool {
       !self.collection.iter().any(|x| other.contains(x))
   }

   pub fn intersection(&amp;self, other: &amp;Self) -&gt; CustomSet&lt;T&gt; {
       CustomSet::new(&amp;self.collection
           .iter()
           .cloned()
           .filter(|c| other.contains(c))
           .collect::&lt;Vec&lt;_&gt;&gt;())
   }

   pub fn union(&amp;self, other: &amp;Self) -&gt; CustomSet&lt;T&gt; {
       CustomSet::new(&amp;self.collection
           .iter()
           .cloned()
           .chain(other.collection.iter().cloned())
           .collect::&lt;Vec&lt;_&gt;&gt;())
   }

   pub fn difference(&amp;self, other: &amp;Self) -&gt; CustomSet&lt;T&gt; {
       CustomSet::new(&amp;self.collection
           .iter()
           .cloned()
           .filter(|c| !other.contains(c))
           .collect::&lt;Vec&lt;_&gt;&gt;())
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-65" id="填充相关-65"><h2>填充/相关</h2></a>
<a class="header" href="#alphametics" id="alphametics"><h1>Alphametics</h1></a>
<a class="header" href="#1-readme-66" id="1-readme-66"><h2>1. Readme</h2></a>
<a class="header" href="#算术谜题" id="算术谜题"><h1>算术谜题</h1></a>
<p>写一个函数来解决字母谜题.</p>
<p><a href="https://en.wikipedia.org/wiki/Alphametics">Alphametics</a>是一个拼图，其中单词中的字母被数字替换.</p>
<p>例如<code>SEND + MORE = MONEY</code>:</p>
<pre><code class="language-text">  S E N D
  M O R E +
-----------
M O N E Y
</code></pre>
<p>用有效数字替换它们会给出:</p>
<pre><code class="language-text">  9 5 6 7
  1 0 8 5 +
-----------
1 0 6 5 2
</code></pre>
<p>这是正确的，因为每个字母都被不同的数字替换，之后单词会被翻译成数字，然后产生有效的总和。</p>
<p>每个字母必须代表不同的数字，并且多位数的首数字不能是 0 。</p>
<p>写一个函数来解决字母谜题.</p>
<a class="header" href="#2-开始你的表演-66" id="2-开始你的表演-66"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::collections::HashMap;

pub fn solve(input: &amp;str) -&gt; Option&lt;HashMap&lt;char, u8&gt;&gt; {
   unimplemented!(&quot;Solve the alphametic {:?}&quot;, input)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-66" id="3-测试代码查看-66"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// use std::collections::HashMap;

fn assert_alphametic_solution_eq(puzzle: &amp;str, solution: &amp;[(char, u8)]) {
   let answer = solve(puzzle);
   let solution: HashMap&lt;char, u8&gt; = solution.iter().cloned().collect();
   assert_eq!(answer, Some(solution));
}

#[test]
fn test_with_three_letters() {
   assert_alphametic_solution_eq(&quot;I + BB == ILL&quot;, &amp;[('I', 1), ('B', 9), ('L', 0)]);
}

#[test]
//#[ignore]
fn test_must_have_unique_value_for_each_letter() {
   let answer = solve(&quot;A == B&quot;);
   assert_eq!(answer, None);
}

#[test]
//#[ignore]
fn test_leading_zero_solution_is_invalid() {
   let answer = solve(&quot;ACA + DD == BD&quot;);
   assert_eq!(answer, None);
}

#[test]
//#[ignore]
fn test_puzzle_with_four_letters() {
   assert_alphametic_solution_eq(&quot;AS + A == MOM&quot;, &amp;[('A', 9), ('S', 2), ('M', 1), ('O', 0)]);
}

#[test]
//#[ignore]
fn test_puzzle_with_six_letters() {
   assert_alphametic_solution_eq(
       &quot;NO + NO + TOO == LATE&quot;,
       &amp;[('N', 7), ('O', 4), ('T', 9), ('L', 1), ('A', 0), ('E', 2)],
   );
}

#[test]
//#[ignore]
fn test_puzzle_with_seven_letters() {
   assert_alphametic_solution_eq(
       &quot;HE + SEES + THE == LIGHT&quot;,
       &amp;[
           ('E', 4),
           ('G', 2),
           ('H', 5),
           ('I', 0),
           ('L', 1),
           ('S', 9),
           ('T', 7),
       ],
   );
}

#[test]
//#[ignore]
fn test_puzzle_with_eight_letters() {
   assert_alphametic_solution_eq(
       &quot;SEND + MORE == MONEY&quot;,
       &amp;[
           ('S', 9),
           ('E', 5),
           ('N', 6),
           ('D', 7),
           ('M', 1),
           ('O', 0),
           ('R', 8),
           ('Y', 2),
       ],
   );
}

#[test]
//#[ignore]
fn test_puzzle_with_ten_letters() {
   assert_alphametic_solution_eq(
       &quot;AND + A + STRONG + OFFENSE + AS + A + GOOD == DEFENSE&quot;,
       &amp;[
           ('A', 5),
           ('D', 3),
           ('E', 4),
           ('F', 7),
           ('G', 8),
           ('N', 0),
           ('O', 2),
           ('R', 1),
           ('S', 6),
           ('T', 9),
       ],
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-66" id="4-答案-66"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// This is a brute-force solution, use `cargo test --release` for faster testing

extern crate itertools;
extern crate permutohedron;

use itertools::Itertools;
use permutohedron::Heap as Permutations;

use std::char;
use std::collections::HashMap;
use std::collections::HashSet;

fn test_equation(puzzle: &amp;str, substitutions: &amp;HashMap&lt;char, u8&gt;) -&gt; bool {
   // Create a new String with characters changed to numbers
   let puzzle: String = puzzle
       .chars()
       .map(|c| {
           if let Some(&amp;n) = substitutions.get(&amp;c) {
               // If the character is in the substitutions, get the number and
               // convert it to a char
               char::from_digit(n as u32, 10).unwrap()
           } else {
               // Otherwise just copy over the character
               c
           }
       })
       .collect();

   // Split the puzzle into left and right side
   let equation: Vec&lt;&amp;str&gt; = puzzle.split(&quot;==&quot;).collect();

   // Parse the number on the right side
   let right = equation[1].trim().parse::&lt;u32&gt;().unwrap();

   // Sum the parts on the left side
   let left: u32 = equation[0]
       .split('+')
       .map(str::trim)
       .map(|n| n.parse::&lt;u32&gt;().unwrap())
       .sum();

   // Create a String with just the numbers and spaces
   let just_numbers = puzzle
       .chars()
       .filter(|c| c.is_digit(10) || c.is_whitespace())
       .collect::&lt;String&gt;();
   // Split this into the numbers and check every number's first character
   let no_leading_zeroes = just_numbers
       .split_whitespace()
       .all(|number| number.chars().next().unwrap() != '0');

   // Return true if left and right side is equal and the equation doesnt
   // contain leading zeroes.
   left == right &amp;&amp; no_leading_zeroes
}

pub fn solve(puzzle: &amp;str) -&gt; Option&lt;HashMap&lt;char, u8&gt;&gt; {
   // Get unique letters from the puzzle
   let letters: HashSet&lt;char&gt; = puzzle
       .chars()
       .filter(|&amp;c| c.is_alphabetic() &amp;&amp; c.is_uppercase())
       .collect();
   let letters: Vec&lt;char&gt; = letters.into_iter().collect();

   // All available numbers for substitution
   let numbers: &amp;[u8] = &amp;[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

   // Iterate every combination with the length of unique letters in the puzzle
   for combinations in numbers.iter().combinations(letters.len()) {
       let mut c = combinations;
       let permutations = Permutations::new(&amp;mut c);
       // Iterate every permutation of a letter combination
       for p in permutations {
           let substitution: HashMap&lt;char, u8&gt; =
               letters.iter().zip(p).map(|(&amp;c, &amp;n)| (c, n)).collect();
           if test_equation(puzzle, &amp;substitution) {
               // We found a good substitution
               return Some(substitution);
           }
       }
   }
   // If we tested every combination and did not found a solution then return None
   None
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-66" id="填充相关-66"><h2>填充/相关</h2></a>
<a class="header" href="#two-bucket" id="two-bucket"><h1>Two Bucket</h1></a>
<a class="header" href="#1-readme-67" id="1-readme-67"><h2>1. Readme</h2></a>
<a class="header" href="#两个桶" id="两个桶"><h1>两个桶</h1></a>
<p>给定两个不同尺寸的桶，演示如何通过两个桶，策略性地传输液体来测量精确的升数.</p>
<p>由于这个数学问题，很容易受到解释/个体方法的影响，因此这些测试代码专门针对期望一个总体解决方案而编写.</p>
<p>为了提供帮助，测试代码首先为桶(1/2)装满。这意味着，若开始时，选择较大的桶装满，那就不会出现，较小的桶装满而较大的桶为空的情况。(也就是说，起点应该用较小桶)；不然这会破坏比较两种方法的目的!</p>
<p>您的程序将作为输入:</p>
<ul>
<li>桶 1 的大小</li>
<li>桶 2 的大小</li>
<li>要达到的理想升数</li>
<li>首先要装满哪个桶，要么是桶 1 还是桶 2</li>
</ul>
<p>您的计划应确定:</p>
<ul>
<li>达到所需的升数，所需的”移动”总数，包括第一次装满</li>
<li>哪个桶应该以所需的升数结束(假设这是桶 A) - 要么桶 1 ，要么桶 2</li>
<li>另一个桶中，剩下多少升(桶 B)</li>
</ul>
<p>注意:任何时候对其中一个或两个桶进行更改，都计为一(1)次移动。</p>
<p>示例：桶 1 最多可容纳 7 升，桶 2 最多可容纳 11 升。让我们说桶 1，第一步，持有 7 升，桶 2 持有 8 升(7，8)。如果您清空桶 1，并且不对桶 2 进行任何更改，则分别为 0 升和 8 升(0，8)，这将作为一个”移动”。相反，如果你已经把桶 1 倒入桶 2，直到桶 2 充满，那留下的，桶 1 中的 4 升和桶 2 中的 11 升(4，11)，这也算作只有一个”移动”。</p>
<p>总而言之，唯一有效的行动是:</p>
<ul>
<li>从一个桶，倒到另一个桶</li>
<li>清空一个桶，对另一个什么都不做</li>
<li>装满一个桶，对另一个什么也不做</li>
</ul>
<p>写&lt;3 于<a href="http://www.fullstackacademy.com/">全栈教程 Academy</a>作 者:Lindsay Levine.</p>
<a class="header" href="#资源-51" id="资源-51"><h2>资源</h2></a>
<p>水浇注问题<a href="http://demonstrations.wolfram.com/WaterPouringProblem/">http://demonstrations.wolfram.com/WaterPouringProblem/</a></p>
<a class="header" href="#2-开始你的表演-67" id="2-开始你的表演-67"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">#[derive(PartialEq, Eq, Debug)]
pub enum Bucket {
   One,
   Two,
}

/// A struct to hold your results in.
#[derive(PartialEq, Eq, Debug)]
pub struct BucketStats {
   /// The total number of &quot;moves&quot; it should take to reach the desired number of liters, including
   /// the first fill.
   pub moves: u8,
   /// Which bucket should end up with the desired number of liters? (Either &quot;one&quot; or &quot;two&quot;)
   pub goal_bucket: Bucket,
   /// How many liters are left in the other bucket?
   pub other_bucket: u8,
}

/// Solve the bucket problem
pub fn solve(capacity_1: u8, capacity_2: u8, goal: u8, start_bucket: &amp;Bucket) -&gt; BucketStats {
   unimplemented!(
       &quot;Given one bucket of capacity {}, another of capacity {}, starting with {:?}, find pours to reach {}&quot;,
       capacity_1,
       capacity_2,
       start_bucket,
       goal,
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-67" id="3-测试代码查看-67"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_case_1() {
   assert_eq!(
       solve(3, 5, 1, &amp;Bucket::One),
       BucketStats {
           moves: 4,
           goal_bucket: Bucket::One,
           other_bucket: 5,
       }
   );
}

#[test]
//#[ignore]
fn test_case_2() {
   assert_eq!(
       solve(3, 5, 1, &amp;Bucket::Two),
       BucketStats {
           moves: 8,
           goal_bucket: Bucket::Two,
           other_bucket: 3,
       }
   );
}

#[test]
//#[ignore]
fn test_case_3() {
   assert_eq!(
       solve(7, 11, 2, &amp;Bucket::One),
       BucketStats {
           moves: 14,
           goal_bucket: Bucket::One,
           other_bucket: 11,
       }
   );
}

#[test]
//#[ignore]
fn test_case_4() {
   assert_eq!(
       solve(7, 11, 2, &amp;Bucket::Two),
       BucketStats {
           moves: 18,
           goal_bucket: Bucket::Two,
           other_bucket: 7,
       }
   );
}

#[test]
//#[ignore]
fn test_case_5() {
   assert_eq!(
       solve(1, 3, 3, &amp;Bucket::Two),
       BucketStats {
           moves: 1,
           goal_bucket: Bucket::Two,
           other_bucket: 0,
       }
   );
}

#[test]
//#[ignore]
fn test_case_6() {
   assert_eq!(
       solve(2, 3, 3, &amp;Bucket::One),
       BucketStats {
           moves: 2,
           goal_bucket: Bucket::Two,
           other_bucket: 2,
       }
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-67" id="4-答案-67"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::{HashSet, VecDeque};

// We can turn this problem into a simple graph searching problem. Each move represents an
// edge in our graph; the buckets' fill states form the graph's vertices. For example, say bucket
// one holds up to 7 liters, and bucket two holds up to 11 liters, and at the current step, bucket
// one has 7 liters and bucket two has 8 liters: (7, 8). By emptying the first bucket, we form an
// edge (7, 8) -&gt; (0, 8). Similarly, by pouring the first bucket into the second, we form an edge
// (7, 8) -&gt; (4, 11).
//
// Since we want to minimize the number of moves, we search the graph breadth-first, starting with
// the configuration provided as the problem input. Note that, to avoid cheating, we mark both
// possible starting configurations as visited; otherwise, our search might just empty the initial
// bucket and fill the other one.

#[derive(PartialEq, Eq, Debug)]
pub enum Bucket {
   One,
   Two,
}

/// A struct to hold your results in.
#[derive(PartialEq, Eq, Debug)]
pub struct BucketStats {
   /// The total number of &quot;moves&quot; it should take to reach the desired number of liters, including
   /// the first fill.
   pub moves: u8,
   /// Which bucket should end up with the desired number of liters? (Either &quot;one&quot; or &quot;two&quot;)
   pub goal_bucket: Bucket,
   /// How many liters are left in the other bucket?
   pub other_bucket: u8,
}

/// Solve the bucket problem
pub fn solve(capacity_1: u8, capacity_2: u8, goal: u8, start_bucket: &amp;Bucket) -&gt; BucketStats {
   let state = match *start_bucket {
       Bucket::One =&gt; (capacity_1, 0),
       Bucket::Two =&gt; (0, capacity_2),
   };

   let mut next_search = VecDeque::new();
   let mut visited = HashSet::new();
   let mut moves = 1;

   next_search.push_front(state);

   // &quot;Visit&quot; both starting states. This will ensure that we don't cheat, i.e.
   // empty our starting bucket completely and fill the other bucket.
   visited.insert((capacity_1, 0));
   visited.insert((0, capacity_2));

   loop {
       let mut current_search = next_search;
       next_search = VecDeque::new();

       for state in current_search.drain(0..) {
           let (bucket_1, bucket_2) = state;

           if bucket_1 == goal {
               return BucketStats {
                   moves: moves,
                   goal_bucket: Bucket::One,
                   other_bucket: bucket_2,
               };
           } else if bucket_2 == goal {
               return BucketStats {
                   moves: moves,
                   goal_bucket: Bucket::Two,
                   other_bucket: bucket_1,
               };
           }

           // Empty the first bucket
           let empty_1 = (0, bucket_2);
           if !visited.contains(&amp;empty_1) {
               next_search.push_front(empty_1);
               visited.insert(empty_1);
           }

           // Empty the second bucket
           let empty_2 = (bucket_1, 0);
           if !visited.contains(&amp;empty_2) {
               next_search.push_front(empty_2);
               visited.insert(empty_2);
           }

           // Fill the first bucket
           let fill_1 = (capacity_1, bucket_2);
           if !visited.contains(&amp;fill_1) {
               next_search.push_front(fill_1);
               visited.insert(fill_1);
           }

           // Fill the second bucket
           let fill_2 = (bucket_1, capacity_2);
           if !visited.contains(&amp;fill_2) {
               next_search.push_front(fill_2);
               visited.insert(fill_2);
           }

           // Pour the first bucket into the second bucket
           let pour_1_into_2 = if bucket_1 + bucket_2 &lt;= capacity_1 {
               (bucket_1 + bucket_2, 0)
           } else {
               (capacity_1, bucket_1 + bucket_2 - capacity_1)
           };
           if !visited.contains(&amp;pour_1_into_2) {
               next_search.push_front(pour_1_into_2);
               visited.insert(pour_1_into_2);
           }

           // Pour the second bucket into the first bucket
           let pour_2_into_1 = if bucket_1 + bucket_2 &lt;= capacity_2 {
               (0, bucket_1 + bucket_2)
           } else {
               (bucket_1 + bucket_2 - capacity_2, capacity_2)
           };
           if !visited.contains(&amp;pour_2_into_1) {
               next_search.push_front(pour_2_into_1);
               visited.insert(pour_2_into_1);
           }
       }

       moves += 1;
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-67" id="填充相关-67"><h2>填充/相关</h2></a>
<a class="header" href="#pig-latin" id="pig-latin"><h1>Pig Latin</h1></a>
<a class="header" href="#1-readme-68" id="1-readme-68"><h2>1. Readme</h2></a>
<a class="header" href="#猪的拉丁文" id="猪的拉丁文"><h1>猪的拉丁文</h1></a>
<p>实现一个从英语翻译成猪拉丁语的程序.</p>
<p>猪拉丁语是一种拼凑的儿童语言，目的是使人困惑。它遵循一些简单的规则(下面)，但是当它说得很快时，对于非儿童(以及非母语者)来说真的很难理解.</p>
<ul>
<li><strong>规则 1</strong>如果一个单词以元音开头，在单词的末尾加上一个”ay”音。请注意，在单词开头的”xr”和”yt”会产生元音(例如 “xray” -&gt; “xrayay”, “yttria” -&gt; “yttriaay”）。</li>
<li><strong>规则 2</strong>如果一个单词以辅音开头，把它移到单词的末尾，然后在单词的末尾加上一个”ay”音。辅音可以由多个辅音组成，例如辅音群(例如”chair” -&gt; “airchay”).</li>
<li><strong>规则 3</strong>如果一个单词以辅音开头，后面跟着”qu”，把它移动到单词的结尾，然后在单词的结尾加上”ay”音(例如，”square” -&gt; “aresquay”).</li>
<li><strong>规则 4</strong>如果一个单词在辅音群后面包含”y”，或者作为两个字母元音的单词的第二个字母(例如，”rhythm” -&gt; “ythmrhay”, “my” -&gt; “ymay”)。</li>
</ul>
<p>边缘案例还有一些规则，也有区域性的变化.</p>
<p>见<a href="http://en.wikipedia.org/wiki/Pig_latin">http://en.wikipedia.org/wiki/Pig_latin</a>更多细节.</p>
<a class="header" href="#资源-52" id="资源-52"><h2>资源</h2></a>
<p>猪拉丁文运动，在第一次超声波教学中的应用<a href="https://github.com/ultrasaurus/test-first-teaching/blob/master/learn_ruby/pig_latin/">https://github.com/ultrasaurus/test-first-teaching/blob/master/learn_ruby/pig_latin/</a></p>
<a class="header" href="#2-开始你的表演-68" id="2-开始你的表演-68"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn translate(input: &amp;str) -&gt; String {
   unimplemented!(
       &quot;Using the Pig Latin text transformation rules, convert the given input '{}'&quot;,
       input
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-68" id="3-测试代码查看-68"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_word_beginning_with_a() {
   assert_eq!(translate(&quot;apple&quot;), &quot;appleay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_e() {
   assert_eq!(translate(&quot;ear&quot;), &quot;earay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_i() {
   assert_eq!(translate(&quot;igloo&quot;), &quot;iglooay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_o() {
   assert_eq!(translate(&quot;object&quot;), &quot;objectay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_u() {
   assert_eq!(translate(&quot;under&quot;), &quot;underay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_a_vowel_and_followed_by_a_qu() {
   assert_eq!(translate(&quot;equal&quot;), &quot;equalay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_p() {
   assert_eq!(translate(&quot;pig&quot;), &quot;igpay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_k() {
   assert_eq!(translate(&quot;koala&quot;), &quot;oalakay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_y() {
   assert_eq!(translate(&quot;yellow&quot;), &quot;ellowyay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_x() {
   assert_eq!(translate(&quot;xenon&quot;), &quot;enonxay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_q_without_a_following_u() {
   assert_eq!(translate(&quot;qat&quot;), &quot;atqay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_ch() {
   assert_eq!(translate(&quot;chair&quot;), &quot;airchay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_qu() {
   assert_eq!(translate(&quot;queen&quot;), &quot;eenquay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_qu_and_a_preceding_consonant() {
   assert_eq!(translate(&quot;square&quot;), &quot;aresquay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_th() {
   assert_eq!(translate(&quot;therapy&quot;), &quot;erapythay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_thr() {
   assert_eq!(translate(&quot;thrush&quot;), &quot;ushthray&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_sch() {
   assert_eq!(translate(&quot;school&quot;), &quot;oolschay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_yt() {
   assert_eq!(translate(&quot;yttria&quot;), &quot;yttriaay&quot;);
}

#[test]
//#[ignore]
fn test_word_beginning_with_xr() {
   assert_eq!(translate(&quot;xray&quot;), &quot;xrayay&quot;);
}

#[test]
//#[ignore]
fn test_y_is_treated_like_a_vowel_at_the_end_of_a_consonant_cluster() {
   assert_eq!(translate(&quot;rhythm&quot;), &quot;ythmrhay&quot;);
}

#[test]
//#[ignore]
fn test_a_whole_phrase() {
   assert_eq!(translate(&quot;quick fast run&quot;), &quot;ickquay astfay unray&quot;);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-68" id="4-答案-68"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[macro_use]
extern crate lazy_static;
extern crate regex;

use regex::Regex;

// Regular expressions from Python version of exercism

pub fn translate_word(word: &amp;str) -&gt; String {
   // Prevent creation and compilation at every call.
   // These are compiled exactly once
   lazy_static! {
       // Detects if it starts with a vowel
       static ref VOWEL: Regex = Regex::new(r&quot;^([aeiou]|y[^aeiou]|xr)[a-z]*&quot;).unwrap();
       // Detects splits for initial consonants
       static ref CONSONANTS: Regex = Regex::new(r&quot;^([^aeiou]?qu|[^aeiou][^aeiouy]*)([a-z]*)&quot;).unwrap();
   }

   if VOWEL.is_match(word) {
       String::from(word) + &quot;ay&quot;
   } else {
       let caps = CONSONANTS.captures(word).unwrap();
       String::from(&amp;caps[2]) + &amp;caps[1] + &quot;ay&quot;
   }
}

pub fn translate(text: &amp;str) -&gt; String {
   text.split(&quot; &quot;)
       .map(|w| translate_word(w))
       .collect::&lt;Vec&lt;_&gt;&gt;()
       .join(&quot; &quot;)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-68" id="填充相关-68"><h2>填充/相关</h2></a>
<a class="header" href="#diamond" id="diamond"><h1>Diamond</h1></a>
<a class="header" href="#1-readme-69" id="1-readme-69"><h2>1. Readme</h2></a>
<a class="header" href="#钻石" id="钻石"><h1>钻石</h1></a>
<p>钻石 kata 将一个字母作为输入，并以菱形输出。给定一个字母，它会打印一个以’A’开头的钻石，并在最宽处提供所提供的字母。</p>
<a class="header" href="#要求-1" id="要求-1"><h2>要求</h2></a>
<ul>
<li>第一行包含一个’A’.</li>
<li>最后一行包含一个’A’.</li>
<li>除第一行和最后一行之外的所有行都有两个完全相同的字母.</li>
<li>所有行都具有与前导空格一样多的尾随空格.(这可能是 0).</li>
<li>钻石是水平对称的.</li>
<li>钻石是垂直对称的.</li>
<li>钻石具有方形(宽度等于高度).</li>
<li>字母形成菱形.</li>
<li>上半部分的字母按升序排列.</li>
<li>下半部分的字母按降序排列.</li>
<li>四个角(包含空格)是三角形.</li>
</ul>
<a class="header" href="#例子-6" id="例子-6"><h2>例子</h2></a>
<p>在以下示例中，空格表示为<code>·</code>字符.</p>
<p>字母’A’的钻石:</p>
<pre><code class="language-text">A
</code></pre>
<p>字母’C’的钻石:</p>
<pre><code class="language-text">··A··
·B·B·
C···C
·B·B·
··A··
</code></pre>
<p>字母’E’的钻石:</p>
<pre><code class="language-text">····A····
···B·B···
··C···C··
·D·····D·
E·······E
·D·····D·
··C···C··
···B·B···
····A····
</code></pre>
<a class="header" href="#资源-53" id="资源-53"><h2>资源</h2></a>
<p>Seb Rose<a href="http://claysnow.co.uk/recycling-tests-in-tdd/">http://claysnow.co.uk/recycling-tests-in-tdd/</a></p>
<a class="header" href="#2-开始你的表演-69" id="2-开始你的表演-69"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn get_diamond(c: char) -&gt; Vec&lt;String&gt; {
   unimplemented!(
       &quot;Return the vector of strings which represent the diamond with particular char {}&quot;,
       c
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-69" id="3-测试代码查看-69"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_a() {
   assert_eq!(get_diamond('A'), vec![&quot;A&quot;]);
}

#[test]
//#[ignore]
fn test_b() {
   assert_eq!(get_diamond('B'), vec![&quot; A &quot;, &quot;B B&quot;, &quot; A &quot;]);
}

#[test]
//#[ignore]
fn test_c() {
   assert_eq!(
       get_diamond('C'),
       vec![&quot;  A  &quot;, &quot; B B &quot;, &quot;C   C&quot;, &quot; B B &quot;, &quot;  A  &quot;]
   );
}

#[test]
//#[ignore]
fn test_d() {
   assert_eq!(
       get_diamond('D'),
       vec![&quot;   A   &quot;, &quot;  B B  &quot;, &quot; C   C &quot;, &quot;D     D&quot;, &quot; C   C &quot;, &quot;  B B  &quot;, &quot;   A   &quot;,]
   );
}

#[test]
//#[ignore]
fn test_e() {
   assert_eq!(
       get_diamond('Z'),
       vec![
           &quot;                         A                         &quot;,
           &quot;                        B B                        &quot;,
           &quot;                       C   C                       &quot;,
           &quot;                      D     D                      &quot;,
           &quot;                     E       E                     &quot;,
           &quot;                    F         F                    &quot;,
           &quot;                   G           G                   &quot;,
           &quot;                  H             H                  &quot;,
           &quot;                 I               I                 &quot;,
           &quot;                J                 J                &quot;,
           &quot;               K                   K               &quot;,
           &quot;              L                     L              &quot;,
           &quot;             M                       M             &quot;,
           &quot;            N                         N            &quot;,
           &quot;           O                           O           &quot;,
           &quot;          P                             P          &quot;,
           &quot;         Q                               Q         &quot;,
           &quot;        R                                 R        &quot;,
           &quot;       S                                   S       &quot;,
           &quot;      T                                     T      &quot;,
           &quot;     U                                       U     &quot;,
           &quot;    V                                         V    &quot;,
           &quot;   W                                           W   &quot;,
           &quot;  X                                             X  &quot;,
           &quot; Y                                               Y &quot;,
           &quot;Z                                                 Z&quot;,
           &quot; Y                                               Y &quot;,
           &quot;  X                                             X  &quot;,
           &quot;   W                                           W   &quot;,
           &quot;    V                                         V    &quot;,
           &quot;     U                                       U     &quot;,
           &quot;      T                                     T      &quot;,
           &quot;       S                                   S       &quot;,
           &quot;        R                                 R        &quot;,
           &quot;         Q                               Q         &quot;,
           &quot;          P                             P          &quot;,
           &quot;           O                           O           &quot;,
           &quot;            N                         N            &quot;,
           &quot;             M                       M             &quot;,
           &quot;              L                     L              &quot;,
           &quot;               K                   K               &quot;,
           &quot;                J                 J                &quot;,
           &quot;                 I               I                 &quot;,
           &quot;                  H             H                  &quot;,
           &quot;                   G           G                   &quot;,
           &quot;                    F         F                    &quot;,
           &quot;                     E       E                     &quot;,
           &quot;                      D     D                      &quot;,
           &quot;                       C   C                       &quot;,
           &quot;                        B B                        &quot;,
           &quot;                         A                         &quot;,
       ]
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-69" id="4-答案-69"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
static ABC: &amp;'static str = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;

pub fn get_diamond(diamond_char: char) -&gt; Vec&lt;String&gt; {
   let mut result: Vec&lt;String&gt; = Vec::new();
   let diamond_char = diamond_char.to_ascii_uppercase();
   if ABC.find(diamond_char).is_none() {
       return result;
   }
   if diamond_char == 'A' {
       return vec![String::from(&quot;A&quot;)];
   }

   //build first half
   for char_in_abc in ABC.chars() {
       result.push(get_line(char_in_abc, diamond_char).clone());
       if char_in_abc == diamond_char {
           break;
       }
   }

   //build second half
   let mut rev = result.clone();
   rev.pop(); //remove middle piece to avoid duplicates
   for line in rev.drain(..).rev() {
       result.push(line);
   }

   result
}

fn get_line(char_in_abc: char, diamond_char: char) -&gt; String {
   let mut r = String::new();
   let letter_e = get_letter_line(char_in_abc);
   let letter_c = get_letter_line(diamond_char);
   let ws = letter_c.len() - letter_e.len(); //number of whitespaces

   //left
   for _ in 0..ws / 2 {
       r.push(' ');
   }
   //letter line
   for i in letter_e.chars() {
       r.push(i)
   }
   //right
   for _ in 0..ws / 2 {
       r.push(' ');
   }
   r
}

fn get_letter_line(char_in_abc: char) -&gt; String {
   let mut r = String::new();
   let odd = (0..)
       .filter(|x| x % 2 != 0)
       .nth(ABC.find(char_in_abc).unwrap())
       .unwrap();
   for i in 0..odd {
       if i == 0 || i == odd - 1 {
           r.push(char_in_abc);
       } else {
           r.push(' ');
       }
   }
   r
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-69" id="填充相关-69"><h2>填充/相关</h2></a>
<a class="header" href="#spiral-matrix" id="spiral-matrix"><h1>Spiral Matrix</h1></a>
<a class="header" href="#1-readme-70" id="1-readme-70"><h2>1. Readme</h2></a>
<a class="header" href="#螺旋矩阵" id="螺旋矩阵"><h1>螺旋矩阵</h1></a>
<p>给定大小，以螺旋顺序返回数字的方阵.</p>
<p>矩阵应填充自然数字，从左上角的 1​​ 开始，以向内，顺时针螺旋顺序增加，如下例所示:</p>
<a class="header" href="#大小为-3-的螺旋矩阵" id="大小为-3-的螺旋矩阵"><h6>大小为 3 的螺旋矩阵</h6></a>
<pre><code class="language-text">1 2 3
8 9 4
7 6 5
</code></pre>
<a class="header" href="#尺寸为-4-的螺旋矩阵" id="尺寸为-4-的螺旋矩阵"><h6>尺寸为 4 的螺旋矩阵</h6></a>
<pre><code class="language-text"> 1  2  3 4
12 13 14 5
11 16 15 6
10  9  8 7
</code></pre>
<a class="header" href="#资源-54" id="资源-54"><h2>资源</h2></a>
<p>Reddit r/dailyprogrammer 挑战 #320 [简单]螺旋升天.<a href="https://www.reddit.com/r/dailyprogrammer/comments/6i60lr/20170619_challenge_320_easy_spiral_ascension/">https://www.reddit.com/r/dailyprogrammer/comments/6i60lr/20170619_challenge_320_easy_spiral_ascension/</a></p>
<a class="header" href="#2-开始你的表演-70" id="2-开始你的表演-70"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn spiral_matrix(size: u32) -&gt; Vec&lt;Vec&lt;u32&gt;&gt; {
   unimplemented!(
       &quot;Function that returns the spiral matrix of square size {}&quot;,
       size
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-70" id="3-测试代码查看-70"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn empty_spiral() {
   let expected: Vec&lt;Vec&lt;u32&gt;&gt; = Vec::new();
   assert_eq!(spiral_matrix(0), expected);
}

#[test]
//#[ignore]
fn size_one_spiral() {
   let mut expected: Vec&lt;Vec&lt;u32&gt;&gt; = Vec::new();
   expected.push(vec![1]);
   assert_eq!(spiral_matrix(1), expected);
}
#[test]
//#[ignore]
fn size_two_spiral() {
   let mut expected: Vec&lt;Vec&lt;u32&gt;&gt; = Vec::new();
   expected.push(vec![1, 2]);
   expected.push(vec![4, 3]);
   assert_eq!(spiral_matrix(2), expected);
}

#[test]
//#[ignore]
fn size_three_spiral() {
   let mut expected: Vec&lt;Vec&lt;u32&gt;&gt; = Vec::new();
   expected.push(vec![1, 2, 3]);
   expected.push(vec![8, 9, 4]);
   expected.push(vec![7, 6, 5]);
   assert_eq!(spiral_matrix(3), expected);
}
#[test]
//#[ignore]
fn size_four_spiral() {
   let mut expected: Vec&lt;Vec&lt;u32&gt;&gt; = Vec::new();
   expected.push(vec![1, 2, 3, 4]);
   expected.push(vec![12, 13, 14, 5]);
   expected.push(vec![11, 16, 15, 6]);
   expected.push(vec![10, 9, 8, 7]);
   assert_eq!(spiral_matrix(4), expected);
}
#[test]
//#[ignore]
fn size_five_spiral() {
   let mut expected: Vec&lt;Vec&lt;u32&gt;&gt; = Vec::new();
   expected.push(vec![1, 2, 3, 4, 5]);
   expected.push(vec![16, 17, 18, 19, 6]);
   expected.push(vec![15, 24, 25, 20, 7]);
   expected.push(vec![14, 23, 22, 21, 8]);
   expected.push(vec![13, 12, 11, 10, 9]);
   assert_eq!(spiral_matrix(5), expected);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-70" id="4-答案-70"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn spiral_matrix(size: u32) -&gt; Vec&lt;Vec&lt;u32&gt;&gt; {
   let mut matrix: Vec&lt;Vec&lt;u32&gt;&gt; = vec![vec![0; size as usize]; size as usize];
   let num_concentric_squares = (size as f64 / 2.0).ceil() as usize;
   let mut counter: u32 = 1;
   let mut sidelen = size as usize;
   for i in 0..num_concentric_squares {
       for j in 0..sidelen {
           matrix[i][i + j] = counter;
           counter += 1;
       }

       for j in 1..sidelen {
           matrix[i + j][size as usize - 1 - i] = counter;
           counter += 1;
       }

       for j in (0..sidelen - 1).rev() {
           matrix[size as usize - 1 - i][i + j] = counter;
           counter += 1;
       }

       for j in (1..sidelen - 1).rev() {
           matrix[i + j][i] = counter;

           counter += 1;
       }
       if sidelen &gt;= 2 {
           sidelen -= 2;
       } else {
           sidelen -= 1;
       }
   }
   matrix
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-70" id="填充相关-70"><h2>填充/相关</h2></a>
<a class="header" href="#palindrome-products" id="palindrome-products"><h1>Palindrome Products</h1></a>
<a class="header" href="#1-readme-71" id="1-readme-71"><h2>1. Readme</h2></a>
<a class="header" href="#回文乘数" id="回文乘数"><h1>回文乘数</h1></a>
<p>在给定范围内，检测回文乘数.</p>
<p>回文数是指当数字倒过来时，保持不变的数。例如,<code>121</code>是回文数，但<code>112</code>不是。</p>
<p>给定一系列数字，找出最大和最小回文，这是该范围内数字的乘积.</p>
<p>您的解决方案应该返回最大和最小回文，以及范围内的每个因素。如果最大或最小回文在范围内，有多于一对的因素，则返回所有的对.</p>
<a class="header" href="#例-1" id="例-1"><h2>例 1</h2></a>
<p>给定范围<code>[1, 9]</code>(包含 1，9)</p>
<p>并给出在这个范围内的列表中，所有可能的乘数:<code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 15, 21, 24, 27, 20, 28, 32, 36, 25, 30, 35, 40, 45, 42, 48, 54, 49, 56, 63, 64, 72, 81]</code></p>
<p>回文乘数都是单数数字(在这种情况下):<code>[1, 2, 3, 4, 5, 6, 7, 8, 9]</code></p>
<p>最小回文乘数是<code>1</code>。 其因素是<code>(1, 1)</code>。 最大回文乘数是<code>9</code>。 其因素是<code>(1, 9)</code>和<code>(3, 3)</code>。</p>
<a class="header" href="#例-2" id="例-2"><h2>例 2</h2></a>
<p>给定范围<code>[10, 99]</code>(包含)</p>
<p>最小回文乘数是<code>121</code>。 其因素是<code>(11, 11)</code>。 最大回文乘数是<code>9009</code>。 其因素是<code>(91, 99)</code>。</p>
<a class="header" href="#资源-55" id="资源-55"><h2>资源</h2></a>
<p>欧拉项目的问题 4<a href="http://projecteuler.net/problem=4">http://projecteuler.net/problem=4</a></p>
<a class="header" href="#2-开始你的表演-71" id="2-开始你的表演-71"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub type Palindrome = u64;
pub fn get_palindrome_products(min: u64, max: u64) -&gt; Vec&lt;Palindrome&gt; {
   unimplemented!(
       &quot;Find all palindromic numbers which are products of numbers in the inclusive range ({}..{})&quot;,
       min,
       max
   )
}

pub fn min(palindromes: &amp;[Palindrome]) -&gt; Option&lt;Palindrome&gt; {
   unimplemented!(
       &quot;Return the palindrome of minimal value from the supplied list: {:?}&quot;,
       palindromes
   )
}

pub fn max(palindromes: &amp;[Palindrome]) -&gt; Option&lt;Palindrome&gt; {
   unimplemented!(
       &quot;Return the palindrome of maximal value from the supplied list: {:?}&quot;,
       palindromes
   )
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-71" id="3-测试代码查看-71"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn single_digits() {
   let palindromes = get_palindrome_products(1, 9);
   assert_eq!(min(&amp;palindromes), Some(1));
   assert_eq!(max(&amp;palindromes), Some(9));
}

#[test]
//#[ignore]
fn double_digits() {
   let palindromes = get_palindrome_products(10, 99);
   assert_eq!(min(&amp;palindromes), Some(121));
   assert_eq!(max(&amp;palindromes), Some(9009));
}

#[test]
//#[ignore]
fn triple_digits() {
   let palindromes = get_palindrome_products(100, 999);
   assert_eq!(min(&amp;palindromes), Some(10201));
   assert_eq!(max(&amp;palindromes), Some(906609));
}

#[test]
//#[ignore]
fn four_digits() {
   let palindromes = get_palindrome_products(1000, 9999);
   assert_eq!(min(&amp;palindromes), Some(1002001));
   assert_eq!(max(&amp;palindromes), Some(99000099));
}

#[test]
//#[ignore]
fn empty_result_for_smallest_palindrome() {
   assert_eq!(min(&amp;get_palindrome_products(1002, 1003)), None);
}

#[test]
//#[ignore]
fn empty_result_for_largest_palindrome() {
   assert_eq!(max(&amp;get_palindrome_products(15, 15)), None);
}

#[test]
//#[ignore]
fn error_smallest_palindrome_when_min_gt_max() {
   assert_eq!(min(&amp;get_palindrome_products(1000, 1)), None);
}

#[test]
//#[ignore]
fn error_largest_palindrome_when_min_st_max() {
   assert_eq!(max(&amp;get_palindrome_products(2, 1)), None);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-71" id="4-答案-71"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub type Palindrome = u64;
pub fn get_palindrome_products(min: u64, max: u64) -&gt; Vec&lt;Palindrome&gt; {
   let mut palindromes: Vec&lt;u64&gt; = Vec::new();
   for i in min..max + 1 {
       for j in min..max + 1 {
           if is_palindrome(i * j) {
               palindromes.push(i * j);
           }
       }
   }
   palindromes
}

pub fn min(palindromes: &amp;[Palindrome]) -&gt; Option&lt;Palindrome&gt; {
   palindromes.iter().min().map(|n| n.clone())
}

pub fn max(palindromes: &amp;[Palindrome]) -&gt; Option&lt;Palindrome&gt; {
   palindromes.iter().max().map(|n| n.clone())
}

fn is_palindrome(n: u64) -&gt; bool {
   let s = n.to_string().into_bytes();
   s.iter().zip(s.iter().rev()).all(|(c1, c2)| c1 == c2)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-71" id="填充相关-71"><h2>填充/相关</h2></a>
<a class="header" href="#poker" id="poker"><h1>Poker</h1></a>
<a class="header" href="#1-readme-72" id="1-readme-72"><h2>1. Readme</h2></a>
<a class="header" href="#扑克" id="扑克"><h1>扑克</h1></a>
<p>从扑克手牌列表中，挑选最好的手牌。</p>
<p>见<a href="https://en.wikipedia.org/wiki/List_of_poker_hands">wikipedia</a>中的扑克手牌概述.</p>
<a class="header" href="#提示-2" id="提示-2"><h2>提示</h2></a>
<ul>
<li>排名扑克手牌可以被认为是一个排序问题.</li>
<li>Rust 提供<a href="https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort">sort</a>方法，用在<code>Vec&lt;T&gt; where T: Ord</code>。</li>
<li><a href="https://doc.rust-lang.org/std/cmp/trait.Ord.html"><code>Ord</code> types</a>是一个<a href="https://en.wikipedia.org/wiki/Total_order">总顺序</a>形式，<code>a &lt; b</code>,<code>a == b</code>或<code>a &gt; b</code>其中一个一定是真的.</li>
<li>扑克手牌不符合一个总顺序：两份手牌可以不相等，但有相同的排序。例子:<code>3S 4S 5D 6H JH&quot;</code>,<code>&quot;3H 4H 5C 6C JD&quot;</code>。</li>
<li>Rust 提供<a href="https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html"><code>PartialOrd</code> trait</a>处理不具有完全顺序的可排序事物的情况。然而，它没有提供标准的<code>sort</code>方法，用于<code>Vec&lt;T&gt; where T: PartialOrd</code>。在这种情况下，对向量进行排序的标准方式是<code>your_vec.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::{Less|Equal|Greater}));</code>这取决于你的需要.`</li>
<li>您可以考虑实现了<code>PartialOrd</code>，表示扑克手牌的类型。</li>
</ul>
<a class="header" href="#资源-56" id="资源-56"><h2>资源</h2></a>
<p>受来自 Udacity 的培训课程的启发.<a href="https://www.udacity.com/course/viewer#!/c-cs212/">https://www.udacity.com/course/viewer#!/c-cs212/</a></p>
<a class="header" href="#2-开始你的表演-72" id="2-开始你的表演-72"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">/// Given a list of poker hands, return a list of those hands which win.
///
/// Note the type signature: this function should return _the same_ reference to
/// the winning hand(s) as were passed in, not reconstructed strings which happen to be equal.
pub fn winning_hands&lt;'a&gt;(hands: &amp;[&amp;'a str]) -&gt; Option&lt;Vec&lt;&amp;'a str&gt;&gt; {
   unimplemented!(&quot;Out of {:?}, which hand wins?&quot;, hands)
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-72" id="3-测试代码查看-72"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// use std::collections::HashSet;

fn hs_from&lt;'a&gt;(input: &amp;[&amp;'a str]) -&gt; HashSet&lt;&amp;'a str&gt; {
   let mut hs = HashSet::new();
   for item in input.iter() {
       hs.insert(*item);
   }
   hs
}

/// Test that the expected output is produced from the given input
/// using the `winning_hands` function.
///
/// Note that the output can be in any order. Here, we use a HashSet to
/// abstract away the order of outputs.
fn test&lt;'a, 'b&gt;(input: &amp;[&amp;'a str], expected: &amp;[&amp;'b str]) {
   assert_eq!(
       hs_from(&amp;winning_hands(input).expect(&quot;This test should produce Some value&quot;,)),
       hs_from(expected)
   )
}

#[test]
fn test_single_hand_always_wins() {
   test(&amp;[&quot;4S 5S 7H 8D JC&quot;], &amp;[&quot;4S 5S 7H 8D JC&quot;])
}

#[test]
//#[ignore]
fn test_highest_card_of_all_hands_wins() {
   test(
       &amp;[&quot;4D 5S 6S 8D 3C&quot;, &quot;2S 4C 7S 9H 10H&quot;, &quot;3S 4S 5D 6H JH&quot;],
       &amp;[&quot;3S 4S 5D 6H JH&quot;],
   )
}

#[test]
//#[ignore]
fn test_a_tie_has_multiple_winners() {
   test(
       &amp;[
           &quot;4D 5S 6S 8D 3C&quot;,
           &quot;2S 4C 7S 9H 10H&quot;,
           &quot;3S 4S 5D 6H JH&quot;,
           &quot;3H 4H 5C 6C JD&quot;,
       ],
       &amp;[&quot;3S 4S 5D 6H JH&quot;, &quot;3H 4H 5C 6C JD&quot;],
   )
}

#[test]
//#[ignore]
fn test_high_card_can_be_low_card_in_an_otherwise_tie() {
   // multiple hands with the same high cards, tie compares next highest ranked,
   // down to last card
   test(&amp;[&quot;3S 5H 6S 8D 7H&quot;, &quot;2S 5D 6D 8C 7S&quot;], &amp;[&quot;3S 5H 6S 8D 7H&quot;])
}

#[test]
//#[ignore]
fn test_one_pair_beats_high_card() {
   test(&amp;[&quot;4S 5H 6C 8D KH&quot;, &quot;2S 4H 6S 4D JH&quot;], &amp;[&quot;2S 4H 6S 4D JH&quot;])
}

#[test]
//#[ignore]
fn test_highest_pair_wins() {
   test(&amp;[&quot;4S 2H 6S 2D JH&quot;, &quot;2S 4H 6C 4D JD&quot;], &amp;[&quot;2S 4H 6C 4D JD&quot;])
}

#[test]
//#[ignore]
fn test_two_pairs_beats_one_pair() {
   test(&amp;[&quot;2S 8H 6S 8D JH&quot;, &quot;4S 5H 4C 8C 5C&quot;], &amp;[&quot;4S 5H 4C 8C 5C&quot;])
}

#[test]
//#[ignore]
fn test_two_pair_ranks() {
   // both hands have two pairs, highest ranked pair wins
   test(&amp;[&quot;2S 8H 2D 8D 3H&quot;, &quot;4S 5H 4C 8S 5D&quot;], &amp;[&quot;2S 8H 2D 8D 3H&quot;])
}

#[test]
//#[ignore]
fn test_two_pairs_second_pair_cascade() {
   // both hands have two pairs, with the same highest ranked pair,
   // tie goes to low pair
   test(&amp;[&quot;2S QS 2C QD JH&quot;, &quot;JD QH JS 8D QC&quot;], &amp;[&quot;JD QH JS 8D QC&quot;])
}

#[test]
//#[ignore]
fn test_two_pairs_last_card_cascade() {
   // both hands have two identically ranked pairs,
   // tie goes to remaining card (kicker)
   test(&amp;[&quot;JD QH JS 8D QC&quot;, &quot;JS QS JC 2D QD&quot;], &amp;[&quot;JD QH JS 8D QC&quot;])
}

#[test]
//#[ignore]
fn test_three_of_a_kind_beats_two_pair() {
   test(&amp;[&quot;2S 8H 2H 8D JH&quot;, &quot;4S 5H 4C 8S 4H&quot;], &amp;[&quot;4S 5H 4C 8S 4H&quot;])
}

#[test]
//#[ignore]
fn test_three_of_a_kind_ranks() {
   //both hands have three of a kind, tie goes to highest ranked triplet
   test(&amp;[&quot;2S 2H 2C 8D JH&quot;, &quot;4S AH AS 8C AD&quot;], &amp;[&quot;4S AH AS 8C AD&quot;])
}

#[test]
//#[ignore]
fn test_three_of_a_kind_cascade_ranks() {
   // with multiple decks, two players can have same three of a kind,
   // ties go to highest remaining cards
   test(&amp;[&quot;4S AH AS 7C AD&quot;, &quot;4S AH AS 8C AD&quot;], &amp;[&quot;4S AH AS 8C AD&quot;])
}

#[test]
//#[ignore]
fn test_straight_beats_three_of_a_kind() {
   test(&amp;[&quot;4S 5H 4C 8D 4H&quot;, &quot;3S 4D 2S 6D 5C&quot;], &amp;[&quot;3S 4D 2S 6D 5C&quot;])
}

#[test]
//#[ignore]
fn test_aces_can_end_a_straight_high() {
   // aces can end a straight (10 J Q K A)
   test(&amp;[&quot;4S 5H 4C 8D 4H&quot;, &quot;10D JH QS KD AC&quot;], &amp;[&quot;10D JH QS KD AC&quot;])
}

#[test]
//#[ignore]
fn test_aces_can_end_a_straight_low() {
   // aces can start a straight (A 2 3 4 5)
   test(&amp;[&quot;4S 5H 4C 8D 4H&quot;, &quot;4D AH 3S 2D 5C&quot;], &amp;[&quot;4D AH 3S 2D 5C&quot;])
}

#[test]
//#[ignore]
fn test_straight_cascade() {
   // both hands with a straight, tie goes to highest ranked card
   test(&amp;[&quot;4S 6C 7S 8D 5H&quot;, &quot;5S 7H 8S 9D 6H&quot;], &amp;[&quot;5S 7H 8S 9D 6H&quot;])
}

#[test]
//#[ignore]
fn test_straight_scoring() {
   // even though an ace is usually high, a 5-high straight is the lowest-scoring straight
   test(&amp;[&quot;2H 3C 4D 5D 6H&quot;, &quot;4S AH 3S 2D 5H&quot;], &amp;[&quot;2H 3C 4D 5D 6H&quot;])
}

#[test]
//#[ignore]
fn test_flush_beats_a_straight() {
   test(&amp;[&quot;4C 6H 7D 8D 5H&quot;, &quot;2S 4S 5S 6S 7S&quot;], &amp;[&quot;2S 4S 5S 6S 7S&quot;])
}

#[test]
//#[ignore]
fn test_flush_cascade() {
   // both hands have a flush, tie goes to high card, down to the last one if necessary
   test(&amp;[&quot;4H 7H 8H 9H 6H&quot;, &quot;2S 4S 5S 6S 7S&quot;], &amp;[&quot;4H 7H 8H 9H 6H&quot;])
}

#[test]
//#[ignore]
fn test_full_house_beats_a_flush() {
   test(&amp;[&quot;3H 6H 7H 8H 5H&quot;, &quot;4S 5C 4C 5D 4H&quot;], &amp;[&quot;4S 5C 4C 5D 4H&quot;])
}

#[test]
//#[ignore]
fn test_full_house_ranks() {
   // both hands have a full house, tie goes to highest-ranked triplet
   test(&amp;[&quot;4H 4S 4D 9S 9D&quot;, &quot;5H 5S 5D 8S 8D&quot;], &amp;[&quot;5H 5S 5D 8S 8D&quot;])
}

#[test]
//#[ignore]
fn test_full_house_cascade() {
   // with multiple decks, both hands have a full house with the same triplet, tie goes to the pair
   test(&amp;[&quot;5H 5S 5D 9S 9D&quot;, &quot;5H 5S 5D 8S 8D&quot;], &amp;[&quot;5H 5S 5D 9S 9D&quot;])
}

#[test]
//#[ignore]
fn test_four_of_a_kind_beats_full_house() {
   test(&amp;[&quot;4S 5H 4D 5D 4H&quot;, &quot;3S 3H 2S 3D 3C&quot;], &amp;[&quot;3S 3H 2S 3D 3C&quot;])
}

#[test]
//#[ignore]
fn test_four_of_a_kind_ranks() {
   // both hands have four of a kind, tie goes to high quad
   test(&amp;[&quot;2S 2H 2C 8D 2D&quot;, &quot;4S 5H 5S 5D 5C&quot;], &amp;[&quot;4S 5H 5S 5D 5C&quot;])
}

#[test]
//#[ignore]
fn test_four_of_a_kind_cascade() {
   // with multiple decks, both hands with identical four of a kind, tie determined by kicker
   test(&amp;[&quot;3S 3H 2S 3D 3C&quot;, &quot;3S 3H 4S 3D 3C&quot;], &amp;[&quot;3S 3H 4S 3D 3C&quot;])
}

#[test]
//#[ignore]
fn test_straight_flush_beats_four_of_a_kind() {
   test(&amp;[&quot;4S 5H 5S 5D 5C&quot;, &quot;7S 8S 9S 6S 10S&quot;], &amp;[&quot;7S 8S 9S 6S 10S&quot;])
}

#[test]
//#[ignore]
fn test_straight_flush_ranks() {
   // both hands have straight flush, tie goes to highest-ranked card
   test(&amp;[&quot;4H 6H 7H 8H 5H&quot;, &quot;5S 7S 8S 9S 6S&quot;], &amp;[&quot;5S 7S 8S 9S 6S&quot;])
}

#}</code></pre></pre>
<a class="header" href="#4-答案-72" id="4-答案-72"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::cmp::Ordering;
use std::fmt;

#[macro_use]
extern crate try_opt;

extern crate counter;
use counter::Counter;

/// Given a list of poker hands, return a list of those hands which win.
///
/// Note the type signature: this function should return _the same_ reference to
/// the winning hand(s) as were passed in, not reconstructed strings which happen to be equal.
pub fn winning_hands&lt;'a&gt;(hands: &amp;[&amp;'a str]) -&gt; Option&lt;Vec&lt;&amp;'a str&gt;&gt; {
   let mut hands = try_opt!(
       hands
           .iter()
           .map(|source| Hand::try_from(source))
           .collect::&lt;Option&lt;Vec&lt;Hand&gt;&gt;&gt;()
   );
   hands.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Less));
   hands.last().map(|last| {
       hands
           .iter()
           .rev()
           .take_while(|&amp;item| item.partial_cmp(last) == Some(Ordering::Equal))
           .map(|hand| hand.source)
           .collect()
   })
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy, Hash)]
enum Suit {
   Spades,
   Clubs,
   Diamonds,
   Hearts,
}

impl Suit {
   fn try_from(source: &amp;str) -&gt; Option&lt;Suit&gt; {
       use Suit::*;
       match source {
           &quot;S&quot; =&gt; Some(Spades),
           &quot;C&quot; =&gt; Some(Clubs),
           &quot;D&quot; =&gt; Some(Diamonds),
           &quot;H&quot; =&gt; Some(Hearts),
           _ =&gt; None,
       }
   }
}

impl fmt::Display for Suit {
   fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
       use Suit::*;
       write!(
           f,
           &quot;{}&quot;,
           match *self {
               Spades =&gt; &quot;S&quot;,
               Clubs =&gt; &quot;C&quot;,
               Diamonds =&gt; &quot;D&quot;,
               Hearts =&gt; &quot;H&quot;,
           }
       )
   }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
enum Rank {
   Number(u8),
   Jack,
   Queen,
   King,
   Ace,
}

impl Rank {
   fn try_from(source: &amp;str) -&gt; Option&lt;Rank&gt; {
       use Rank::*;
       match source {
           &quot;A&quot; =&gt; Some(Ace),
           &quot;K&quot; =&gt; Some(King),
           &quot;Q&quot; =&gt; Some(Queen),
           &quot;J&quot; =&gt; Some(Jack),
           &quot;10&quot; =&gt; Some(Number(10)),
           &quot;9&quot; =&gt; Some(Number(9)),
           &quot;8&quot; =&gt; Some(Number(8)),
           &quot;7&quot; =&gt; Some(Number(7)),
           &quot;6&quot; =&gt; Some(Number(6)),
           &quot;5&quot; =&gt; Some(Number(5)),
           &quot;4&quot; =&gt; Some(Number(4)),
           &quot;3&quot; =&gt; Some(Number(3)),
           &quot;2&quot; =&gt; Some(Number(2)),
           _ =&gt; None,
       }
   }

   fn value(&amp;self) -&gt; usize {
       use Rank::*;
       match *self {
           Ace =&gt; 14,
           King =&gt; 13,
           Queen =&gt; 12,
           Jack =&gt; 11,
           Number(n) =&gt; n as usize,
       }
   }
}

impl fmt::Display for Rank {
   fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
       use Rank::*;
       let num_str; // early declaration to placate NLL of Number case
       write!(
           f,
           &quot;{}&quot;,
           match *self {
               Ace =&gt; &quot;A&quot;,
               King =&gt; &quot;K&quot;,
               Queen =&gt; &quot;Q&quot;,
               Jack =&gt; &quot;J&quot;,
               Number(n) =&gt; {
                   num_str = n.to_string();
                   &amp;num_str
               }
           }
       )
   }
}

impl PartialOrd for Rank {
   fn partial_cmp(&amp;self, other: &amp;Rank) -&gt; Option&lt;Ordering&gt; {
       Some(self.value().cmp(&amp;other.value()))
   }
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Clone, Copy)]
struct Card {
   rank: Rank,
   suit: Suit,
}

impl Card {
   fn try_from_split(source: &amp;str, split: usize) -&gt; Option&lt;Card&gt; {
       Some(Card {
           rank: try_opt!(Rank::try_from(&amp;source[..split])),
           suit: try_opt!(Suit::try_from(&amp;source[split..])),
       })
   }

   fn try_from(source: &amp;str) -&gt; Option&lt;Card&gt; {
       match source.len() {
           3 =&gt; Card::try_from_split(source, 2),
           2 =&gt; Card::try_from_split(source, 1),
           _ =&gt; None,
       }
   }
}

impl fmt::Display for Card {
   fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
       write!(f, &quot;{}{}&quot;, self.rank, self.suit)
   }
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum PokerHand {
   HighCard,
   OnePair,
   TwoPair,
   ThreeOfAKind,
   Straight,
   Flush,
   FullHouse,
   FourOfAKind,
   StraightFlush,
}

impl PokerHand {
   fn is_ace_low_straight(cards: &amp;[Card]) -&gt; bool {
       // special case: ace-low straight
       // still depends on the sorted precondition
       cards[0].rank.value() == 2 &amp;&amp; cards[4].rank == Rank::Ace
           &amp;&amp; cards
               .windows(2)
               .take(3) // (0, 1), (1, 2), (2, 3) --&gt; skips 4, ace
               .map(|pair| pair[1].rank.value() - pair[0].rank.value())
               .all(|diff| diff == 1)
   }

   fn analyze(cards: &amp;[Card]) -&gt; Option&lt;PokerHand&gt; {
       if cards.len() == 5 {
           let suit_counter = Counter::init(cards.iter().map(|c| c.suit));
           let is_flush = suit_counter
               .most_common()
               .map(|(_suit, count)| count)
               .next() == Some(5);
           // Note that `is_straight` depends on a precondition: it only works
           // if the input `cards` are sorted by rank value ascending.
           let is_straight = cards
               .windows(2)
               .map(|pair| pair[1].rank.value() - pair[0].rank.value())
               .all(|diff| diff == 1)
               || PokerHand::is_ace_low_straight(cards);

           if is_flush &amp;&amp; is_straight {
               return Some(PokerHand::StraightFlush);
           }

           let rank_counter = Counter::init(cards.iter().map(|c| c.rank));
           let mut rc_iter = rank_counter.most_common().map(|(_rank, count)| count);
           let rc_most = rc_iter.next();
           let rc_second = rc_iter.next();

           if rc_most == Some(4) {
               return Some(PokerHand::FourOfAKind);
           }
           if rc_most == Some(3) &amp;&amp; rc_second == Some(2) {
               return Some(PokerHand::FullHouse);
           }
           if is_flush {
               return Some(PokerHand::Flush);
           }
           if is_straight {
               return Some(PokerHand::Straight);
           }
           if rc_most == Some(3) {
               return Some(PokerHand::ThreeOfAKind);
           }
           if rc_most == Some(2) &amp;&amp; rc_second == Some(2) {
               return Some(PokerHand::TwoPair);
           }
           if rc_most == Some(2) {
               return Some(PokerHand::OnePair);
           }
           Some(PokerHand::HighCard)
       } else {
           None
       }
   }
}

#[derive(Debug, PartialEq, Eq)]
struct Hand&lt;'a&gt; {
   source: &amp;'a str,
   cards: [Card; 5],
   hand_type: PokerHand,
}

impl&lt;'a&gt; Hand&lt;'a&gt; {
   fn try_from(source: &amp;'a str) -&gt; Option&lt;Hand&gt; {
       let mut cards = try_opt!(
           source
               .split_whitespace()
               .map(|s| Card::try_from(s))
               .collect::&lt;Option&lt;Vec&lt;Card&gt;&gt;&gt;()
       );
       cards.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Less));
       if cards.len() == 5 {
           Some(Hand {
               source: source,
               cards: [cards[0], cards[1], cards[2], cards[3], cards[4]],
               hand_type: try_opt!(PokerHand::analyze(&amp;cards)),
           })
       } else {
           None
       }
   }

   fn cmp_high_card(&amp;self, other: &amp;Hand, card: usize) -&gt; Ordering {
       let mut ordering = self.cards[card]
           .rank
           .value()
           .cmp(&amp;other.cards[card].rank.value());
       if card != 0 {
           ordering = ordering.then_with(|| self.cmp_high_card(other, card - 1));
       }
       ordering
   }

   fn value_by_frequency(&amp;self) -&gt; (Option&lt;Rank&gt;, Option&lt;Rank&gt;, Option&lt;Rank&gt;) {
       let rank_counter = Counter::init(self.cards.iter().map(|c| c.rank));
       let mut rc_iter = rank_counter
           .most_common_tiebreaker(|a, b| b.partial_cmp(a).unwrap_or(Ordering::Less))
           .map(|(rank, _count)| rank);
       (rc_iter.next(), rc_iter.next(), rc_iter.next())
   }

   fn cmp_cascade_by_freq(&amp;self, other: &amp;Hand) -&gt; Ordering {
       let (s1, s2, s3) = self.value_by_frequency();
       let (o1, o2, o3) = other.value_by_frequency();
       s1.partial_cmp(&amp;o1)
           .map(|c| {
               c.then(
                   s2.partial_cmp(&amp;o2)
                       .map(|c2| c2.then(s3.partial_cmp(&amp;o3).unwrap_or(Ordering::Equal)))
                       .unwrap_or(Ordering::Equal),
               )
           })
           .unwrap_or(Ordering::Equal)
   }

   fn cmp_straight(&amp;self, other: &amp;Hand) -&gt; Ordering {
       let s = if PokerHand::is_ace_low_straight(&amp;self.cards) {
           5
       } else {
           self.cards[4].rank.value()
       };
       let o = if PokerHand::is_ace_low_straight(&amp;other.cards) {
           5
       } else {
           other.cards[4].rank.value()
       };
       s.cmp(&amp;o)
   }
}

impl&lt;'a&gt; fmt::Display for Hand&lt;'a&gt; {
   fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
       write!(f, &quot;{}&quot;, self.source)
   }
}

impl&lt;'a&gt; PartialOrd for Hand&lt;'a&gt; {
   fn partial_cmp(&amp;self, other: &amp;Hand) -&gt; Option&lt;Ordering&gt; {
       Some(self.hand_type.cmp(&amp;other.hand_type).then_with(|| {
           use PokerHand::*;
           match self.hand_type {
               HighCard =&gt; self.cmp_high_card(other, 4),
               OnePair =&gt; self.cmp_cascade_by_freq(other),
               TwoPair =&gt; self.cmp_cascade_by_freq(other),
               ThreeOfAKind =&gt; self.cmp_cascade_by_freq(other),
               Straight =&gt; self.cmp_straight(other),
               Flush =&gt; self.cmp_high_card(other, 4),
               FullHouse =&gt; self.cmp_cascade_by_freq(other),
               FourOfAKind =&gt; self.cmp_cascade_by_freq(other),
               StraightFlush =&gt; self.cmp_straight(other),
           }
       }))
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-72" id="填充相关-72"><h2>填充/相关</h2></a>
<a class="header" href="#grep" id="grep"><h1>Grep</h1></a>
<a class="header" href="#1-readme-73" id="1-readme-73"><h2>1. Readme</h2></a>
<a class="header" href="#grep-1" id="grep-1"><h1>grep</h1></a>
<p>在文件中，搜索与正则表达式模式匹配的行。返回每个匹配行的行号和内容.</p>
<p>Unix<a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html"><code>grep</code></a>命令可用于搜索，与用户提供的搜索查询匹配的一个或多个文件中的行(称为<em>模式</em>).</p>
<p>该<code>grep</code>命令有三个参数:</p>
<ol>
<li>用于匹配文件中的行的模式.</li>
<li>零个或多个标志以自定义匹配行为.</li>
<li>一个或多个要搜索匹配行的文件.</li>
</ol>
<p>你的任务是实现<code>grep</code>函数，应该读取指定文件的内容，找到与指定模式匹配的行，然后将这些行输出为单个字符串。请注意，行应按其找到的顺序输出，第一个文件中的第一个匹配行首先输出。</p>
<p>例如，假设有一个名为”input.txt”的文件，其中包含以下内容:</p>
<pre><code class="language-text">hello
world
hello again
</code></pre>
<p>如果我们打电话<code>grep &quot;hello&quot; input.txt</code>，返回的字符串应该是:</p>
<pre><code class="language-text">hello
hello again
</code></pre>
<a class="header" href="#旗" id="旗"><h3>旗</h3></a>
<p>如前所述，<code>grep</code>命令还应该支持以下标志:</p>
<ul>
<li><code>-n</code>打印每个匹配行的行号.</li>
<li><code>-l</code>仅打印包含至少一个匹配行的文件的名称.</li>
<li><code>-i</code>使用不区分大小写的比较匹配行.</li>
<li><code>-v</code>反转程序 - 收集所有与模式不匹配的行.</li>
<li><code>-x</code>仅匹配整行，而不是匹配包含匹配的行.</li>
</ul>
<p>如果我们运行<code>grep -n &quot;hello&quot; input.txt</code>，<code>-n</code>flag 将要求匹配的行以其行号作为前缀:</p>
<pre><code class="language-text">1:hello
3:hello again
</code></pre>
<p>如果我们运行<code>grep -i &quot;HELLO&quot; input.txt</code>，我们将做一个不区分大小写的匹配，输出将是:</p>
<pre><code class="language-text">hello
hello again
</code></pre>
<p>该<code>grep</code>命令应该一次支持多个标志.</p>
<p>例如，运行<code>grep -l -v &quot;hello&quot; file1.txt file2.txt</code>应该打印不包含字符串”hello”的文件的名称.</p>
<a class="header" href="#错误处理" id="错误处理"><h3>错误处理</h3></a>
<p>本练习介绍了该用法<code>failure</code>箱子，它为您提供了管理自定义错误类型的方法。要了解有关箱子的更多信息，请参阅<a href="https://boats.gitlab.io/failure/intro.html">failure 文档</a></p>
<a class="header" href="#补充阅读" id="补充阅读"><h3>补充阅读</h3></a>
<p>虽然本练习要求您只实现最基本的<code>grep</code>函数，实际上是有一个完全的，重新实现的<code>grep</code>Rust 项目 -<a href="https://github.com/BurntSushi/ripgrep">ripgrep</a>.</p>
<p>如果您喜欢在 Rust 中，重写基本工具程序的概念，请务必检查以下项目:</p>
<ul>
<li><a href="https://github.com/sharkdp/fd">fd</a>- 复刻<code>find</code></li>
<li><a href="https://github.com/ogham/exa">exa</a>- 复刻<code>ls</code></li>
<li><a href="https://github.com/sharkdp/bat">bat</a>- 复刻<code>cat</code></li>
<li><a href="https://github.com/uutils/coreutils">coreutils</a>- 重写 GNU coreutils</li>
</ul>
<a class="header" href="#资源-57" id="资源-57"><h2>资源</h2></a>
<p>与 Nate Foster 的对话.<a href="http://www.cs.cornell.edu/Courses/cs3110/2014sp/hw/0/ps0.pdf">http://www.cs.cornell.edu/Courses/cs3110/2014sp/hw/0/ps0.pdf</a></p>
<a class="header" href="#2-开始你的表演-73" id="2-开始你的表演-73"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">extern crate failure;

use failure::Error;

/// While using raw slice of str to handle flags is convenient,
/// in the real-world projects it is customary to use a struct,
/// that contains flags-related logic. So in this exercise
/// we ask you to implement a custom struct.
///
/// If you are curious about real-world implementation, refer to the `clap-rs` crate:
/// https://github.com/kbknapp/clap-rs/blob/master/src/args/arg_matches.rs
#[derive(Debug)]
pub struct Flags;

impl Flags {
   pub fn new(flags: &amp;[&amp;str]) -&gt; Self {
       unimplemented!(
           &quot;Given the flags {:?} implement your own 'Flags' struct to handle flags-related logic&quot;,
           flags
       );
   }
}

pub fn grep(pattern: &amp;str, flags: &amp;Flags, files: &amp;[&amp;str]) -&gt; Result&lt;Vec&lt;String&gt;, Error&gt; {
   unimplemented!(
       &quot;Search the files '{:?}' for '{}' pattern and save the matches in a vector. Your search logic should be aware of the given flags '{:?}'&quot;,
       files,
       pattern,
       flags
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-73" id="3-测试代码查看-73"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::fs;

static ILIAD_CONTENT: &amp;'static str = &quot;Achilles sing, O Goddess! Peleus' son;
His wrath pernicious, who ten thousand woes
Caused to Achaia's host, sent many a soul
Illustrious into Ades premature,
And Heroes gave (so stood the will of Jove)
To dogs and to all ravening fowls a prey,
When fierce dispute had separated once
The noble Chief Achilles from the son
Of Atreus, Agamemnon, King of men.
&quot;;

static MIDSUMMER_NIGHT_CONTENT: &amp;'static str = &quot;I do entreat your grace to pardon me.
I know not by what power I am made bold,
Nor how it may concern my modesty,
In such a presence here to plead my thoughts;
But I beseech your grace that I may know
The worst that may befall me in this case,
If I refuse to wed Demetrius.
&quot;;

static PARADISE_LOST_CONTENT: &amp;'static str = &quot;Of Mans First Disobedience, and the Fruit
Of that Forbidden Tree, whose mortal tast
Brought Death into the World, and all our woe,
With loss of Eden, till one greater Man
Restore us, and regain the blissful Seat,
Sing Heav'nly Muse, that on the secret top
Of Oreb, or of Sinai, didst inspire
That Shepherd, who first taught the chosen Seed
&quot;;

/// In The White Night
/// A poem by Alexander Blok(https://en.wikipedia.org/wiki/Alexander_Blok)
/// a Russian poet who is regarded as one of the most important figures of the Silver Age of Russian Poetry
/// You can read the translation here: https://lyricstranslate.com/ru/белой-ночью-месяц-красный-white-night-crimson-crescent.html
static IN_THE_WHITE_NIGHT_CONTENT: &amp;'static str = &quot;Белой ночью месяц красный
Выплывает в синеве.
Бродит призрачно-прекрасный,
Отражается в Неве.
Мне провидится и снится
Исполпенье тайных дум.
В вас ли доброе таится,
Красный месяц, тихий шум?..
&quot;;

struct Fixture&lt;'a&gt; {
   file_names: &amp;'a [&amp;'a str],
}

impl&lt;'a&gt; Fixture&lt;'a&gt; {
   fn new(file_names: &amp;'a [&amp;'a str]) -&gt; Self {
       Fixture { file_names }
   }

   fn set_up(&amp;self) {
       let file_name_content_pairs = self
           .file_names
           .iter()
           .cloned()
           .map(|file_name| {
               if file_name.ends_with(&quot;iliad.txt&quot;) {
                   (file_name, ILIAD_CONTENT)
               } else if file_name.ends_with(&quot;midsummer_night.txt&quot;) {
                   (file_name, MIDSUMMER_NIGHT_CONTENT)
               } else if file_name.ends_with(&quot;paradise_lost.txt&quot;) {
                   (file_name, PARADISE_LOST_CONTENT)
               } else {
                   (file_name, IN_THE_WHITE_NIGHT_CONTENT)
               }
           })
           .collect::&lt;Vec&lt;(&amp;str, &amp;str)&gt;&gt;();

       set_up_files(&amp;file_name_content_pairs);
   }
}

impl&lt;'a&gt; Drop for Fixture&lt;'a&gt; {
   fn drop(&amp;mut self) {
       tear_down_files(self.file_names);
   }
}

fn set_up_files(files: &amp;[(&amp;str, &amp;str)]) {
   for (file_name, file_content) in files {
       fs::write(file_name, file_content).expect(&amp;format!(
           &quot;Error setting up file '{}' with the following content:\n{}&quot;,
           file_name, file_content
       ));
   }
}

fn tear_down_files(files: &amp;[&amp;str]) {
   for file_name in files {
       fs::remove_file(file_name).expect(&amp;format!(&quot;Could not delete file '{}'&quot;, file_name));
   }
}

/// This macro is here so that every test case had its own set of files to be used in test.
/// The approach is to create required files for every test case and to append test name to the
/// file names (so for test with a name 'test_one_file_one_match_no_flags' and a required file
/// 'iliad.txt' there would be created a file with a name
/// 'test_one_file_one_match_no_flags_iliad.txt').
/// This allows us to create files for every test case with no intersection between them.
///
/// A better way would be to create required set of files at the start of tests run and to
/// delete them after every test is finished, but there is no trivial way to create such
/// a test fixture in standard Rust, and Exercism restricts the usage of external dependencies
/// in test files. Therefore the above approach is chosen.
///
/// If you have an idea about a better way to implement test fixture for this exercise,
/// please submit PR to the Rust Exercism track: https://github.com/exercism/rust
macro_rules! set_up_test_case {
   ($(#[$flag:meta])+ $test_case_name:ident(pattern=$pattern:expr, flags=[$($grep_flag:expr),*], files=[$($file:expr),+], expected=[$($expected:expr),*])) =&gt; {
       $(#[$flag])+
       fn $test_case_name() {
           let pattern = $pattern;

           let flags = vec![$($grep_flag),*];

           let files = vec![$(concat!(stringify!($test_case_name), &quot;_&quot; , $file)),+];

           let expected = vec![$($expected),*];

           process_grep_case(&amp;pattern, &amp;flags, &amp;files, &amp;expected);
       }
   };
   ($(#[$flag:meta])+ $test_case_name:ident(pattern=$pattern:expr, flags=[$($grep_flag:expr),*], files=[$($file:expr),+], prefix_expected=[$($expected:expr),*])) =&gt; {
       $(#[$flag])+
       fn $test_case_name() {
           let pattern = $pattern;

           let flags = vec![$($grep_flag),*];

           let files = vec![$(concat!(stringify!($test_case_name), &quot;_&quot; , $file)),+];

           let expected = vec![$(concat!(stringify!($test_case_name), &quot;_&quot;, $expected)),*];

           process_grep_case(&amp;pattern, &amp;flags, &amp;files, &amp;expected);
       }

   }
}

fn process_grep_case(pattern: &amp;str, flags: &amp;[&amp;str], files: &amp;[&amp;str], expected: &amp;[&amp;str]) {
   let test_fixture = Fixture::new(files);

   test_fixture.set_up();

   let flags = Flags::new(flags);

   let grep_result = grep(pattern, &amp;flags, files).unwrap();

   assert_eq!(grep_result, expected);
}

// Test returning a Result

#[test]
fn test_nonexistent_file_returns_error() {
   let pattern = &quot;Agamemnon&quot;;

   let flags = Flags::new(&amp;vec![]);

   let files = vec![&quot;test_nonexistent_file_returns_error_iliad.txt&quot;];

   assert!(grep(&amp;pattern, &amp;flags, &amp;files).is_err());
}

#[test]
//#[ignore]
fn test_grep_returns_result() {
   let pattern = &quot;Agamemnon&quot;;

   let flags = Flags::new(&amp;vec![]);

   let files = vec![&quot;test_grep_returns_result_iliad.txt&quot;];

   let test_fixture = Fixture::new(&amp;files);

   test_fixture.set_up();

   assert!(grep(&amp;pattern, &amp;flags, &amp;files).is_ok());
}

// Test grepping a single file

set_up_test_case!(#[test]
//#[ignore]
test_one_file_one_match_no_flags(
   pattern = &quot;Agamemnon&quot;,
   flags = [],
   files = [&quot;iliad.txt&quot;],
   expected = [&quot;Of Atreus, Agamemnon, King of men.&quot;]
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_one_match_print_line_numbers_flag(
   pattern = &quot;Forbidden&quot;,
   flags = [&quot;-n&quot;],
   files = [&quot;paradise_lost.txt&quot;],
   expected = [&quot;2:Of that Forbidden Tree, whose mortal tast&quot;]
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_one_match_caseinsensitive_flag(
   pattern = &quot;FORBIDDEN&quot;,
   flags = [&quot;-i&quot;],
   files = [&quot;paradise_lost.txt&quot;],
   expected = [&quot;Of that Forbidden Tree, whose mortal tast&quot;]
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_one_match_print_file_names_flag(
   pattern = &quot;Forbidden&quot;,
   flags = [&quot;-l&quot;],
   files = [&quot;paradise_lost.txt&quot;],
   prefix_expected = [&quot;paradise_lost.txt&quot;]
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_one_match_match_entire_lines_flag(
   pattern = &quot;With loss of Eden, till one greater Man&quot;,
   flags = [&quot;-x&quot;],
   files = [&quot;paradise_lost.txt&quot;],
   expected = [&quot;With loss of Eden, till one greater Man&quot;]
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_one_match_multiple_flags(
   pattern = &quot;OF ATREUS, Agamemnon, KIng of MEN.&quot;,
   flags = [&quot;-x&quot;, &quot;-i&quot;, &quot;-n&quot;],
   files = [&quot;iliad.txt&quot;],
   expected = [&quot;9:Of Atreus, Agamemnon, King of men.&quot;]
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_several_matches_no_flags(
   pattern = &quot;may&quot;,
   flags = [],
   files = [&quot;midsummer_night.txt&quot;],
   expected = [
       &quot;Nor how it may concern my modesty,&quot;,
       &quot;But I beseech your grace that I may know&quot;,
       &quot;The worst that may befall me in this case,&quot;
   ]
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_several_matches_print_line_numbers_flag(
   pattern = &quot;may&quot;,
   flags = [&quot;-n&quot;],
   files = [&quot;midsummer_night.txt&quot;],
   expected = [
       &quot;3:Nor how it may concern my modesty,&quot;,
       &quot;5:But I beseech your grace that I may know&quot;,
       &quot;6:The worst that may befall me in this case,&quot;
   ]
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_several_matches_match_entire_lines_flag(
   pattern = &quot;may&quot;,
   flags = [&quot;-x&quot;],
   files = [&quot;midsummer_night.txt&quot;],
   expected = []
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_several_matches_caseinsensitive_flag(
   pattern = &quot;ACHILLES&quot;,
   flags = [&quot;-i&quot;],
   files = [&quot;iliad.txt&quot;],
   expected = [
       &quot;Achilles sing, O Goddess! Peleus' son;&quot;,
       &quot;The noble Chief Achilles from the son&quot;
   ]
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_several_matches_inverted_flag(
   pattern = &quot;Of&quot;,
   flags = [&quot;-v&quot;],
   files = [&quot;paradise_lost.txt&quot;],
   expected = [
       &quot;Brought Death into the World, and all our woe,&quot;,
       &quot;With loss of Eden, till one greater Man&quot;,
       &quot;Restore us, and regain the blissful Seat,&quot;,
       &quot;Sing Heav'nly Muse, that on the secret top&quot;,
       &quot;That Shepherd, who first taught the chosen Seed&quot;
   ]
));

set_up_test_case!(#[test]
//#[ignore]
test_one_file_no_matches_various_flags(
   pattern = &quot;Gandalf&quot;,
   flags = [&quot;-n&quot;, &quot;-l&quot;, &quot;-x&quot;, &quot;-i&quot;],
   files = [&quot;iliad.txt&quot;],
   expected = []
));

// Test grepping multiples files at once

set_up_test_case!(#[test]
//#[ignore]
test_multiple_files_one_match_no_flags(
   pattern = &quot;Agamemnon&quot;,
   flags = [],
   files = [&quot;iliad.txt&quot;, &quot;midsummer_night.txt&quot;, &quot;paradise_lost.txt&quot;],
   prefix_expected = [&quot;iliad.txt:Of Atreus, Agamemnon, King of men.&quot;]
));

set_up_test_case!(#[test]
//#[ignore]
test_multiple_files_several_matches_no_flags(
   pattern = &quot;may&quot;,
   flags = [],
   files = [&quot;iliad.txt&quot;, &quot;midsummer_night.txt&quot;, &quot;paradise_lost.txt&quot;],
   prefix_expected = [
       &quot;midsummer_night.txt:Nor how it may concern my modesty,&quot;,
       &quot;midsummer_night.txt:But I beseech your grace that I may know&quot;,
       &quot;midsummer_night.txt:The worst that may befall me in this case,&quot;
   ]
));

set_up_test_case!(#[test]
//#[ignore]
test_multiple_files_several_matches_print_line_numbers_flag(
   pattern = &quot;that&quot;,
   flags = [&quot;-n&quot;],
   files = [&quot;iliad.txt&quot;, &quot;midsummer_night.txt&quot;, &quot;paradise_lost.txt&quot;],
   prefix_expected = [
       &quot;midsummer_night.txt:5:But I beseech your grace that I may know&quot;,
       &quot;midsummer_night.txt:6:The worst that may befall me in this case,&quot;,
       &quot;paradise_lost.txt:2:Of that Forbidden Tree, whose mortal tast&quot;,
       &quot;paradise_lost.txt:6:Sing Heav'nly Muse, that on the secret top&quot;
   ]
));

set_up_test_case!(#[test]
//#[ignore]
test_multiple_files_one_match_print_file_names_flag(
   pattern = &quot;who&quot;,
   flags = [&quot;-l&quot;],
   files = [&quot;iliad.txt&quot;, &quot;midsummer_night.txt&quot;, &quot;paradise_lost.txt&quot;],
   prefix_expected = [&quot;iliad.txt&quot;, &quot;paradise_lost.txt&quot;]
));

set_up_test_case!(#[test]
//#[ignore]
test_multiple_files_several_matches_caseinsensitive_flag(
   pattern = &quot;TO&quot;,
   flags = [&quot;-i&quot;],
   files = [&quot;iliad.txt&quot;, &quot;midsummer_night.txt&quot;, &quot;paradise_lost.txt&quot;],
   prefix_expected = [
       &quot;iliad.txt:Caused to Achaia's host, sent many a soul&quot;,
       &quot;iliad.txt:Illustrious into Ades premature,&quot;,
       &quot;iliad.txt:And Heroes gave (so stood the will of Jove)&quot;,
       &quot;iliad.txt:To dogs and to all ravening fowls a prey,&quot;,
       &quot;midsummer_night.txt:I do entreat your grace to pardon me.&quot;,
       &quot;midsummer_night.txt:In such a presence here to plead my thoughts;&quot;,
       &quot;midsummer_night.txt:If I refuse to wed Demetrius.&quot;,
       &quot;paradise_lost.txt:Brought Death into the World, and all our woe,&quot;,
       &quot;paradise_lost.txt:Restore us, and regain the blissful Seat,&quot;,
       &quot;paradise_lost.txt:Sing Heav'nly Muse, that on the secret top&quot;
   ]
));

set_up_test_case!(
   #[test]
   //#[ignore]
   test_multiple_files_several_matches_caseinsensitive_flag_utf8(
       pattern = &quot;В&quot;, // This letter stands for cyrillic 'Ve' and not latin 'B'. Therefore there should be no matches from paradise_lost.txt
       flags = [&quot;-i&quot;],
       files = [&quot;paradise_lost.txt&quot;, &quot;in_the_white_night.txt&quot;],
       prefix_expected = [
           &quot;in_the_white_night.txt:Выплывает в синеве.&quot;,
           &quot;in_the_white_night.txt:Отражается в Неве.&quot;,
           &quot;in_the_white_night.txt:Мне провидится и снится&quot;,
           &quot;in_the_white_night.txt:В вас ли доброе таится,&quot;
       ]
   )
);

set_up_test_case!(#[test]
//#[ignore]
test_multiple_files_several_matches_inverted_flag(
   pattern = &quot;a&quot;,
   flags = [&quot;-v&quot;],
   files = [&quot;iliad.txt&quot;, &quot;midsummer_night.txt&quot;, &quot;paradise_lost.txt&quot;],
   prefix_expected = [
       &quot;iliad.txt:Achilles sing, O Goddess! Peleus' son;&quot;,
       &quot;iliad.txt:The noble Chief Achilles from the son&quot;,
       &quot;midsummer_night.txt:If I refuse to wed Demetrius.&quot;
   ]
));

set_up_test_case!(#[test]
//#[ignore]
test_multiple_files_one_match_match_entire_lines_flag(
   pattern = &quot;But I beseech your grace that I may know&quot;,
   flags = [&quot;-x&quot;],
   files = [&quot;iliad.txt&quot;, &quot;midsummer_night.txt&quot;, &quot;paradise_lost.txt&quot;],
   prefix_expected = [&quot;midsummer_night.txt:But I beseech your grace that I may know&quot;]
));

set_up_test_case!(#[test]
//#[ignore]
test_multiple_files_one_match_multiple_flags(
   pattern = &quot;WITH LOSS OF EDEN, TILL ONE GREATER MAN&quot;,
   flags = [&quot;-n&quot;, &quot;-i&quot;, &quot;-x&quot;],
   files = [&quot;iliad.txt&quot;, &quot;midsummer_night.txt&quot;, &quot;paradise_lost.txt&quot;],
   prefix_expected = [&quot;paradise_lost.txt:4:With loss of Eden, till one greater Man&quot;]
));

set_up_test_case!(#[test]
//#[ignore]
test_multiple_files_no_matches_various_flags(
   pattern = &quot;Frodo&quot;,
   flags = [&quot;-n&quot;, &quot;-i&quot;, &quot;-x&quot;, &quot;-l&quot;],
   files = [&quot;iliad.txt&quot;, &quot;midsummer_night.txt&quot;, &quot;paradise_lost.txt&quot;],
   expected = []
));

#}</code></pre></pre>
<a class="header" href="#4-答案-73" id="4-答案-73"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[macro_use]
extern crate failure;

use failure::Error;
use std::{fs, path::Path};

#[derive(Debug, Fail)]
enum FileAccessError {
   #[fail(display = &quot;File not found: {}&quot;, file_name)]
   FileNotFoundError { file_name: String },

   #[fail(display = &quot;Error reading file: {}&quot;, file_name)]
   FileReadError { file_name: String },
}

pub struct Flags {
   print_line_number: bool,
   print_file_name: bool,
   use_caseinsensitive_comparison: bool,
   use_inverted_comparison: bool,
   match_entire_line: bool,
}

impl Flags {
   pub fn new(flags: &amp;[&amp;str]) -&gt; Self {
       Flags {
           print_line_number: flags.contains(&amp;&quot;-n&quot;),
           print_file_name: flags.contains(&amp;&quot;-l&quot;),
           use_caseinsensitive_comparison: flags.contains(&amp;&quot;-i&quot;),
           use_inverted_comparison: flags.contains(&amp;&quot;-v&quot;),
           match_entire_line: flags.contains(&amp;&quot;-x&quot;),
       }
   }
}

fn get_file_lines(file_name: &amp;str) -&gt; Result&lt;Vec&lt;String&gt;, FileAccessError&gt; {
   let file_path = Path::new(file_name);

   if !file_path.exists() {
       return Err(FileAccessError::FileNotFoundError {
           file_name: String::from(file_name),
       });
   }

   if let Ok(content) = fs::read_to_string(file_path) {
       Ok(content.split(&quot;\n&quot;).map(|line| line.to_string()).collect())
   } else {
       Err(FileAccessError::FileReadError {
           file_name: String::from(file_name),
       })
   }
}

pub fn grep(pattern: &amp;str, flags: &amp;Flags, files: &amp;[&amp;str]) -&gt; Result&lt;Vec&lt;String&gt;, Error&gt; {
   let mut grep_result = vec![];

   let is_multiple_file_search = files.len() &gt; 1;

   for file_name in files {
       let file_lines = get_file_lines(file_name)?;

       grep_result.extend(
           file_lines
               .iter()
               .enumerate()
               .filter(|&amp;(_, line)| {
                   let mut inner_line = String::from(line.clone());

                   let mut inner_pattern = String::from(pattern);

                   if flags.use_caseinsensitive_comparison {
                       inner_line = inner_line.to_lowercase().to_string();

                       inner_pattern = inner_pattern.to_lowercase().to_string();
                   }

                   let mut is_filtered = inner_line.contains(&amp;inner_pattern);

                   if flags.match_entire_line {
                       is_filtered = inner_line == inner_pattern;
                   }

                   if flags.use_inverted_comparison {
                       is_filtered = !inner_line.contains(&amp;inner_pattern);
                   }

                   is_filtered
               })
               .filter(|(_, line)| !line.is_empty())
               .map(|(line_number, line)| {
                   let mut result = line.to_owned();

                   if flags.print_line_number {
                       result.insert_str(0, &amp;format!(&quot;{}:&quot;, line_number + 1));
                   }

                   if is_multiple_file_search {
                       result.insert_str(0, &amp;format!(&quot;{}:&quot;, file_name))
                   }

                   if flags.print_file_name {
                       result = file_name.to_owned().to_owned();
                   }

                   result
               }),
       );
   }

   grep_result.dedup_by(|a, b| (*a).eq(b));

   Ok(grep_result)
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-73" id="填充相关-73"><h2>填充/相关</h2></a>
<a class="header" href="#scale-generator" id="scale-generator"><h1>Scale Generator</h1></a>
<a class="header" href="#1-readme-74" id="1-readme-74"><h2>1. Readme</h2></a>
<a class="header" href="#音阶生成器" id="音阶生成器"><h1>音阶生成器</h1></a>
<blockquote>
<p>译：真不知道说什么。</p>
</blockquote>
<p>给出一个音调，或是开始的音符以及一组间隔，从音调开始并遵循指定的间隔模式生成音阶。</p>
<p>西方音乐中的音阶，基于彩色(12 音符)音阶。该音阶可表示为以下一组音高:</p>
<p>A，A#，B，C，C#，D，D#，E，F，F#，G，G#</p>
<p>给出一个尖音符(用#表示)也可以表示为它前面的平音符(用 b 表示)，所以半音音阶也可以这样写:</p>
<p>A，Bb，B，C，Db，D，Eb，E，F，Gb，G，Ab</p>
<p>大调和小调的音阶和模式是这个十二音高集合的子集。它们有七个音高，称为全音阶音阶。这些音阶中的音符集合使用锐利或平面，根据音调。这是一个列表，其中包括:</p>
<p>没有尖(Sharps)或平(Flats)：C 大调（major）和 a 小调(minor)</p>
<p>使用 Sharps:
G, D, A, E, B, F# major
e, b, f#, c#, g#, d# minor</p>
<p>使用 Flats:
F, Bb, Eb, Ab, Db, Gb major
d, g, c, f, bb, eb minor</p>
<p>全音阶音阶以及源自半音音阶的所有其他音阶都是间隔建立的。间隔是两个音高之间的间距。</p>
<p>最简单的间隔是在两个相邻音符之间，称为”半步”或”小秒”(有时写为小写”m”)。具有中间音符的两个音符之间的间隔称为”整步”或”大秒”(写为大写”M”)。仅使用相邻音符之间的这两个间隔，来构建全音阶音阶。</p>
<p>非全音阶音阶可以包含其他间隔。一个”先增强”的间隔，写上 A，具有两个中间音符(例如，从 A 到 C 或从 D 到 E)。间隔也越来越小，但他们不会参与这个练习。</p>
<a class="header" href="#2-开始你的表演-74" id="2-开始你的表演-74"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">// You should change this.
//
// Depending on your implementation, there are a variety of potential errors
// which might occur. They aren't checked by the test suite in order to
// allow the greatest freedom of implementation, but real libraries should
// provide useful, descriptive errors so that downstream code can react
// appropriately.
//
// One common idiom is to define an Error enum which wraps all potential
// errors. Another common idiom is to use a helper type such as failure::Error
// which does more or less the same thing but automatically.
pub type Error = ();

pub struct Scale;

impl Scale {
   pub fn new(tonic: &amp;str, intervals: &amp;str) -&gt; Result&lt;Scale, Error&gt; {
       unimplemented!(
           &quot;Construct a new scale with tonic {} and intervals {}&quot;,
           tonic,
           intervals
       )
   }

   pub fn chromatic(tonic: &amp;str) -&gt; Result&lt;Scale, Error&gt; {
       unimplemented!(&quot;Construct a new chromatic scale with tonic {}&quot;, tonic)
   }

   pub fn enumerate(&amp;self) -&gt; Vec&lt;String&gt; {
       unimplemented!()
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-74" id="3-测试代码查看-74"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
/// Tests for scale-generator
///
/// Generated by [script][script] using [canonical data][canonical-data]
///
/// [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
/// [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/scale-generator/canonical_data.json

/// Process a single test case for the property `chromatic`
///
/// All cases for the `chromatic` property are implemented
/// in terms of this function.
fn process_chromatic_case(tonic: &amp;str, expected: &amp;[&amp;str]) {
   let s = Scale::chromatic(tonic).unwrap();
   assert_eq!(s.enumerate(), expected);
}

/// Process a single test case for the property `interval`
///
/// All cases for the `interval` property are implemented
/// in terms of this function.
fn process_interval_case(tonic: &amp;str, intervals: &amp;str, expected: &amp;[&amp;str]) {
   let s = Scale::new(tonic, intervals).unwrap();
   assert_eq!(s.enumerate(), expected);
}

// Chromatic scales
// These tests have no interval.
// The chromatic scale is considered the default scale

#[test]
/// Chromatic scale with sharps
fn test_chromatic_scale_with_sharps() {
   process_chromatic_case(
       &quot;C&quot;,
       &amp;[
           &quot;C&quot;, &quot;C#&quot;, &quot;D&quot;, &quot;D#&quot;, &quot;E&quot;, &quot;F&quot;, &quot;F#&quot;, &quot;G&quot;, &quot;G#&quot;, &quot;A&quot;, &quot;A#&quot;, &quot;B&quot;,
       ],
   );
}

#[test]
//#[ignore]
/// Chromatic scale with flats
fn test_chromatic_scale_with_flats() {
   process_chromatic_case(
       &quot;F&quot;,
       &amp;[
           &quot;F&quot;, &quot;Gb&quot;, &quot;G&quot;, &quot;Ab&quot;, &quot;A&quot;, &quot;Bb&quot;, &quot;B&quot;, &quot;C&quot;, &quot;Db&quot;, &quot;D&quot;, &quot;Eb&quot;, &quot;E&quot;,
       ],
   );
}

// Scales with specified intervals
// These tests all have intervals and are explorations of different
// traversals of the scale.

#[test]
//#[ignore]
/// Simple major scale
///
/// The simplest major scale, with no sharps or flats.
fn test_simple_major_scale() {
   process_interval_case(&quot;C&quot;, &quot;MMmMMMm&quot;, &amp;[&quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;A&quot;, &quot;B&quot;]);
}

#[test]
//#[ignore]
/// Major scale with sharps
fn test_major_scale_with_sharps() {
   process_interval_case(&quot;G&quot;, &quot;MMmMMMm&quot;, &amp;[&quot;G&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F#&quot;]);
}

#[test]
//#[ignore]
/// Major scale with flats
fn test_major_scale_with_flats() {
   process_interval_case(&quot;F&quot;, &quot;MMmMMMm&quot;, &amp;[&quot;F&quot;, &quot;G&quot;, &quot;A&quot;, &quot;Bb&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;]);
}

#[test]
//#[ignore]
/// Minor scale with sharps
fn test_minor_scale_with_sharps() {
   process_interval_case(&quot;f#&quot;, &quot;MmMMmMM&quot;, &amp;[&quot;F#&quot;, &quot;G#&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C#&quot;, &quot;D&quot;, &quot;E&quot;]);
}

#[test]
//#[ignore]
/// Minor scale with flats
fn test_minor_scale_with_flats() {
   process_interval_case(&quot;bb&quot;, &quot;MmMMmMM&quot;, &amp;[&quot;Bb&quot;, &quot;C&quot;, &quot;Db&quot;, &quot;Eb&quot;, &quot;F&quot;, &quot;Gb&quot;, &quot;Ab&quot;]);
}

#[test]
//#[ignore]
/// Dorian mode
fn test_dorian_mode() {
   process_interval_case(&quot;d&quot;, &quot;MmMMMmM&quot;, &amp;[&quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;]);
}

#[test]
//#[ignore]
/// Mixolydian mode
fn test_mixolydian_mode() {
   process_interval_case(&quot;Eb&quot;, &quot;MMmMMmM&quot;, &amp;[&quot;Eb&quot;, &quot;F&quot;, &quot;G&quot;, &quot;Ab&quot;, &quot;Bb&quot;, &quot;C&quot;, &quot;Db&quot;]);
}

#[test]
//#[ignore]
/// Lydian mode
fn test_lydian_mode() {
   process_interval_case(&quot;a&quot;, &quot;MMMmMMm&quot;, &amp;[&quot;A&quot;, &quot;B&quot;, &quot;C#&quot;, &quot;D#&quot;, &quot;E&quot;, &quot;F#&quot;, &quot;G#&quot;]);
}

#[test]
//#[ignore]
/// Phrygian mode
fn test_phrygian_mode() {
   process_interval_case(&quot;e&quot;, &quot;mMMMmMM&quot;, &amp;[&quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;]);
}

#[test]
//#[ignore]
/// Locrian mode
fn test_locrian_mode() {
   process_interval_case(&quot;g&quot;, &quot;mMMmMMM&quot;, &amp;[&quot;G&quot;, &quot;Ab&quot;, &quot;Bb&quot;, &quot;C&quot;, &quot;Db&quot;, &quot;Eb&quot;, &quot;F&quot;]);
}

#[test]
//#[ignore]
/// Harmonic minor
///
/// Note that this case introduces the accidental interval (A)
fn test_harmonic_minor() {
   process_interval_case(&quot;d&quot;, &quot;MmMMmAm&quot;, &amp;[&quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;A&quot;, &quot;Bb&quot;, &quot;Db&quot;]);
}

#[test]
//#[ignore]
/// Octatonic
fn test_octatonic() {
   process_interval_case(
       &quot;C&quot;,
       &quot;MmMmMmMm&quot;,
       &amp;[&quot;C&quot;, &quot;D&quot;, &quot;D#&quot;, &quot;F&quot;, &quot;F#&quot;, &quot;G#&quot;, &quot;A&quot;, &quot;B&quot;],
   );
}

#[test]
//#[ignore]
/// Hexatonic
fn test_hexatonic() {
   process_interval_case(&quot;Db&quot;, &quot;MMMMMM&quot;, &amp;[&quot;Db&quot;, &quot;Eb&quot;, &quot;F&quot;, &quot;G&quot;, &quot;A&quot;, &quot;B&quot;]);
}

#[test]
//#[ignore]
/// Pentatonic
fn test_pentatonic() {
   process_interval_case(&quot;A&quot;, &quot;MMAMA&quot;, &amp;[&quot;A&quot;, &quot;B&quot;, &quot;C#&quot;, &quot;E&quot;, &quot;F#&quot;]);
}

#[test]
//#[ignore]
/// Enigmatic
fn test_enigmatic() {
   process_interval_case(&quot;G&quot;, &quot;mAMMMmm&quot;, &amp;[&quot;G&quot;, &quot;G#&quot;, &quot;B&quot;, &quot;C#&quot;, &quot;D#&quot;, &quot;F&quot;, &quot;F#&quot;]);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-74" id="4-答案-74"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[macro_use]
extern crate enum_primitive_derive;
extern crate failure;
#[macro_use]
extern crate failure_derive;
extern crate itertools;
extern crate num_traits;

pub use self::interval::{Interval, Intervals};
use self::note::Accidental;
pub use self::note::Note;
use failure::Error;
use std::str::FromStr;

pub mod interval {
   use itertools::Itertools;
   use std::fmt;
   use std::ops::Deref;
   use std::str::FromStr;

   #[derive(Debug, Clone, Copy, PartialEq, Eq, Fail)]
   pub enum ParseErr {
       #[fail(display = &quot;invalid interval&quot;)]
       InvalidInterval,
       #[fail(display = &quot;wrong number of semitones&quot;)]
       WrongNumberOfSemitones,
   }

   #[derive(Debug, Clone, Copy, PartialEq, Eq, Primitive)]
   pub enum Interval {
       HalfStep = 1,
       WholeStep = 2,
       AugmentedFirst = 3,
   }

   impl fmt::Display for Interval {
       fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
           use self::Interval::*;
           write!(
               f,
               &quot;{}&quot;,
               match self {
                   HalfStep =&gt; &quot;m&quot;,
                   WholeStep =&gt; &quot;M&quot;,
                   AugmentedFirst =&gt; &quot;A&quot;,
               }
           )
       }
   }

   impl FromStr for Interval {
       type Err = ParseErr;

       fn from_str(s: &amp;str) -&gt; Result&lt;Self, Self::Err&gt; {
           use self::Interval::*;
           match s {
               &quot;m&quot; =&gt; Ok(HalfStep),
               &quot;M&quot; =&gt; Ok(WholeStep),
               &quot;A&quot; =&gt; Ok(AugmentedFirst),
               _ =&gt; Err(ParseErr::InvalidInterval),
           }
       }
   }

   #[derive(Debug, Clone, PartialEq, Eq)]
   pub struct Intervals(Vec&lt;Interval&gt;);

   impl fmt::Display for Intervals {
       fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
           write!(f, &quot;{}&quot;, self.0.iter().join(&quot;&quot;))
       }
   }

   impl FromStr for Intervals {
       type Err = ParseErr;

       fn from_str(s: &amp;str) -&gt; Result&lt;Self, Self::Err&gt; {
           let mut semitones = Vec::with_capacity(s.len());

           for (i, c) in s.char_indices() {
               semitones.push(Interval::from_str(&amp;s[i..i + c.len_utf8()])?);
           }

           if semitones.iter().take(12).map(|&amp;i| i as u8).sum::&lt;u8&gt;() == 12 {
               Ok(Intervals(semitones))
           } else {
               Err(ParseErr::WrongNumberOfSemitones)
           }
       }
   }

   impl Deref for Intervals {
       type Target = Vec&lt;Interval&gt;;

       fn deref(&amp;self) -&gt; &amp;Self::Target {
           &amp;self.0
       }
   }

   #[cfg(test)]
   mod test {
       use super::*;

       #[test]
       fn test_parse_chromatic() {
           assert!(&quot;mmmmmmmmmmmm&quot;.parse::&lt;Intervals&gt;().is_ok());
       }

       #[test]
       fn test_parse_major() {
           assert!(&quot;MMmMMMm&quot;.parse::&lt;Intervals&gt;().is_ok());
       }

       #[test]
       fn test_parse_minor() {
           assert!(&quot;MmMMmMM&quot;.parse::&lt;Intervals&gt;().is_ok());
       }
   }
}

pub mod note {
   use interval::Interval;
   use num_traits::{FromPrimitive, ToPrimitive};
   use std::fmt;
   use std::ops::AddAssign;
   use std::str::FromStr;

   pub const SEMITONES: i8 = 12;

   #[derive(Debug, Clone, Copy, PartialEq, Eq, Primitive)]
   pub enum Semitone {
       A = 0,
       ASharp = 1,
       B = 2,
       C = 3,
       CSharp = 4,
       D = 5,
       DSharp = 6,
       E = 7,
       F = 8,
       FSharp = 9,
       G = 10,
       GSharp = 11,
   }

   #[derive(Debug, Clone, Copy, PartialEq, Eq, Primitive)]
   pub enum Root {
       A = 0,
       B = 2,
       C = 3,
       D = 5,
       E = 7,
       F = 8,
       G = 10,
   }

   impl fmt::Display for Root {
       fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
           write!(f, &quot;{:?}&quot;, self)
       }
   }

   #[derive(Debug, Clone, Copy, PartialEq, Eq)]
   pub enum Accidental {
       Sharp,
       Flat,
   }

   impl Accidental {
       fn to_i8(&amp;self) -&gt; i8 {
           match *self {
               Accidental::Sharp =&gt; 1,
               Accidental::Flat =&gt; -1,
           }
       }

       pub fn from_tonic(tonic: &amp;str) -&gt; Accidental {
           match tonic {
               &quot;C&quot; | &quot;a&quot; | &quot;G&quot; | &quot;D&quot; | &quot;A&quot; | &quot;E&quot; | &quot;B&quot; | &quot;F#&quot; | &quot;e&quot; | &quot;b&quot; | &quot;f#&quot; | &quot;c#&quot; | &quot;g#&quot;
               | &quot;d#&quot; =&gt; Accidental::Sharp,
               _ =&gt; Accidental::Flat,
           }
       }
   }

   impl fmt::Display for Accidental {
       fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
           write!(
               f,
               &quot;{}&quot;,
               match &amp;self {
                   Accidental::Sharp =&gt; '#',
                   Accidental::Flat =&gt; 'b',
               }
           )
       }
   }

   #[derive(Debug, Clone, Copy, PartialEq, Eq)]
   pub struct Note {
       tonic: Root,
       accidental: Option&lt;Accidental&gt;,
   }

   impl Note {
       pub fn canonicalize(&amp;self, lean: Accidental) -&gt; Note {
           let mut n: Note = Semitone::from(*self).into();
           if let Some(accidental) = n.accidental {
               if accidental != lean {
                   if lean == Accidental::Flat {
                       n += Interval::HalfStep;
                       n.accidental = Some(Accidental::Flat);
                   }
               }
           }
           n
       }
   }

   impl fmt::Display for Note {
       fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
           write!(
               f,
               &quot;{}{}&quot;,
               self.tonic,
               self.accidental.map_or(String::new(), |a| a.to_string()),
           )
       }
   }

   #[derive(Debug, Clone, Copy, PartialEq, Eq, Fail)]
   pub enum ParseErr {
       #[fail(display = &quot;invalid length&quot;)]
       InvalidLength,
       #[fail(display = &quot;invalid tonic&quot;)]
       InvalidTonic,
       #[fail(display = &quot;invalid accidental&quot;)]
       InvalidAccidental,
   }

   impl FromStr for Note {
       type Err = ParseErr;

       fn from_str(s: &amp;str) -&gt; Result&lt;Self, Self::Err&gt; {
           let lc = s.to_lowercase();
           let mut iter = lc.chars();

           let mut note = match iter.next() {
               Some(c) if 'a' &lt;= c &amp;&amp; 'g' &gt;= c =&gt; Note {
                   tonic: match c {
                       'a' =&gt; Root::A,
                       'b' =&gt; Root::B,
                       'c' =&gt; Root::C,
                       'd' =&gt; Root::D,
                       'e' =&gt; Root::E,
                       'f' =&gt; Root::F,
                       'g' =&gt; Root::G,
                       _ =&gt; return Err(ParseErr::InvalidTonic),
                   },
                   accidental: None,
               },
               Some(_) =&gt; return Err(ParseErr::InvalidTonic),
               None =&gt; return Err(ParseErr::InvalidLength),
           };

           match iter.next() {
               Some('b') =&gt; note.accidental = Some(Accidental::Flat),
               Some('#') =&gt; note.accidental = Some(Accidental::Sharp),
               Some(_) =&gt; return Err(ParseErr::InvalidAccidental),
               None =&gt; {}
           }

           if iter.next().is_some() {
               return Err(ParseErr::InvalidLength);
           }

           Ok(note)
       }
   }

   impl From&lt;Semitone&gt; for Note {
       fn from(s: Semitone) -&gt; Self {
           Note {
               tonic: match s {
                   Semitone::A | Semitone::ASharp =&gt; Root::A,
                   Semitone::B =&gt; Root::B,
                   Semitone::C | Semitone::CSharp =&gt; Root::C,
                   Semitone::D | Semitone::DSharp =&gt; Root::D,
                   Semitone::E =&gt; Root::E,
                   Semitone::F | Semitone::FSharp =&gt; Root::F,
                   Semitone::G | Semitone::GSharp =&gt; Root::G,
               },
               accidental: match s {
                   Semitone::ASharp
                   | Semitone::CSharp
                   | Semitone::DSharp
                   | Semitone::FSharp
                   | Semitone::GSharp =&gt; Some(Accidental::Sharp),
                   _ =&gt; None,
               },
           }
       }
   }

   impl From&lt;Note&gt; for Semitone {
       fn from(n: Note) -&gt; Self {
           Semitone::from_i8(
               (SEMITONES + n.tonic.to_i8().unwrap() + n.accidental.map_or(0, |a| a.to_i8()))
                   % SEMITONES,
           ).expect(&quot;must have valid semitone&quot;)
       }
   }

   impl AddAssign&lt;Interval&gt; for Note {
       fn add_assign(&amp;mut self, rhs: Interval) {
           *self = Semitone::from_i8(
               (SEMITONES + Semitone::from(*self).to_i8().unwrap() + rhs.to_i8().unwrap())
                   % SEMITONES,
           ).unwrap()
               .into();
       }
   }

}

#[derive(Debug)]
pub struct Scale {
   tonic: Note,
   lean: Accidental,
   intervals: Intervals,
}

impl Scale {
   pub fn new(tonic: &amp;str, intervals: &amp;str) -&gt; Result&lt;Scale, Error&gt; {
       Ok(Scale {
           tonic: Note::from_str(tonic)?,
           lean: Accidental::from_tonic(tonic),
           intervals: Intervals::from_str(intervals)?,
       })
   }

   pub fn chromatic(tonic: &amp;str) -&gt; Result&lt;Scale, Error&gt; {
       Scale::new(tonic, &quot;mmmmmmmmmmmm&quot;)
   }

   pub fn enumerate(&amp;self) -&gt; Vec&lt;String&gt; {
       let mut out = Vec::with_capacity(self.intervals.len());

       let mut note = self.tonic;
       for &amp;interval in self.intervals.iter() {
           out.push(note.canonicalize(self.lean).to_string());
           note += interval;
       }

       out
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-74" id="填充相关-74"><h2>填充/相关</h2></a>
<a class="header" href="#decimal" id="decimal"><h1>Decimal</h1></a>
<a class="header" href="#1-readme-75" id="1-readme-75"><h2>1. Readme</h2></a>
<a class="header" href="#十进制" id="十进制"><h1>十进制</h1></a>
<p>实现任意精度的<code>Decimal</code>类。</p>
<p>浮点数是计算中非整数实数的最常见表示，它们是由<a href="https://en.wikipedia.org/wiki/IEEE_754">IEEE 754</a>标准定义。它们非常灵活且通用，但它们确实有一些局限性。众所周知，在浮点运算中，<a href="http://0.30000000000000004.com/"><code>0.1 + 0.2 != 0.3</code></a>。</p>
<p>解决这一问题的方法是，寻找另一种无损的方法来模拟任意精度的非整数 实数。这可能在内存或处理速度方面，不如浮点数有效；但目标是提供准确的结果。</p>
<p>尽管<code>Decimal</code>作为一种自定义类型，我们仍然应该能够将它们视为数字: 而<code>==</code>，<code>&lt;</code>，<code>&gt;</code>，<code>+</code>，<code>-</code>和<code>*</code>操作符都应该按小数进行工作。只是权宜之计，你不需要执行除法，因为任意的精确除法很快就会失控。(如何表示任意精度<code>1/3</code>?)</p>
<p>在 Rust 中，将这些操作用于自定义类型的方法是，实现自定义对象的相关 trait。特别是，您至少需要实现.<code>PartialEq</code>，<code>PartialOrd</code>，<code>Add</code>，<code>Sub</code>和<code>Mul</code>。 严格地说，由于十进制数构成一个总排序，你也应该实现<code>Eq</code>和<code>Ord</code>，尽管这些 trait 并没有被这些测试所检验.</p>
<a class="header" href="#笔记-4" id="笔记-4"><h1>笔记</h1></a>
<p>使用这种.<a href="https://crates.io/crates/bigdecimal">bigdecimal</a>箱子方法很容易实现这个练习。但不要那样做，你自己来实现。</p>
<a class="header" href="#提示-3" id="提示-3"><h1>提示</h1></a>
<ul>
<li>不要从头开始执行任意精确的算术，而是考虑在<a href="https://crates.io/crates/num-bigint">num_bigint</a>箱子之上构建自己的类。</li>
<li>你也许能<a href="https://doc.rust-lang.org/book/appendix-03-derivable-traits.html">derive</a>一些需要的 trait。</li>
<li><code>Decimal</code>假设为符号类型。你不必创建一个单独的无符号类型，尽管你可以这样做，如果你选择这么样，能作为一个实现细节。</li>
</ul>
<a class="header" href="#资源-58" id="资源-58"><h2>资源</h2></a>
<p>Peter Goodspeed-Niklaus</p>
<a class="header" href="#2-开始你的表演-75" id="2-开始你的表演-75"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">/// Type implementing arbitrary-precision decimal arithmetic
pub struct Decimal {
   // implement your type here
}

impl Decimal {
   pub fn try_from(input: &amp;str) -&gt; Option&lt;Decimal&gt; {
       unimplemented!(&quot;Create a new decimal with a value of {}&quot;, input)
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-75" id="3-测试代码查看-75"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
/// Create a Decimal from a string literal
///
/// Use only when you _know_ that your value is valid.
fn decimal(input: &amp;str) -&gt; Decimal {
   Decimal::try_from(input).expect(&quot;That was supposed to be a valid value&quot;)
}

/// Some big and precise values we can use for testing. [0] + [1] == [2]
const BIGS: [&amp;'static str; 3] = [
   &quot;100000000000000000000000000000000000000000000.00000000000000000000000000000000000000001&quot;,
   &quot;100000000000000000000000000000000000000000000.00000000000000000000000000000000000000002&quot;,
   &quot;200000000000000000000000000000000000000000000.00000000000000000000000000000000000000003&quot;,
];

// test simple properties of required operations
#[test]
fn test_eq() {
   assert!(decimal(&quot;0.0&quot;) == decimal(&quot;0.0&quot;));
   assert!(decimal(&quot;1.0&quot;) == decimal(&quot;1.0&quot;));
   for big in BIGS.iter() {
       assert!(decimal(big) == decimal(big));
   }
}

#[test]
//#[ignore]
fn test_ne() {
   assert!(decimal(&quot;0.0&quot;) != decimal(&quot;1.0&quot;));
   assert!(decimal(BIGS[0]) != decimal(BIGS[1]));
}

#[test]
//#[ignore]
fn test_gt() {
   for slice_2 in BIGS.windows(2) {
       assert!(decimal(slice_2[1]) &gt; decimal(slice_2[0]));
       assert!(!(decimal(slice_2[0]) &gt; decimal(slice_2[1])));
   }
}

#[test]
//#[ignore]
fn test_lt() {
   for slice_2 in BIGS.windows(2) {
       assert!(decimal(slice_2[0]) &lt; decimal(slice_2[1]));
       assert!(!(decimal(slice_2[1]) &lt; decimal(slice_2[0])));
   }
}

#[test]
//#[ignore]
fn test_add() {
   assert_eq!(decimal(&quot;0.1&quot;) + decimal(&quot;0.2&quot;), decimal(&quot;0.3&quot;));
   assert_eq!(decimal(BIGS[0]) + decimal(BIGS[1]), decimal(BIGS[2]));
   assert_eq!(decimal(BIGS[1]) + decimal(BIGS[0]), decimal(BIGS[2]));
}

#[test]
//#[ignore]
fn test_sub() {
   assert_eq!(decimal(BIGS[2]) - decimal(BIGS[1]), decimal(BIGS[0]));
   assert_eq!(decimal(BIGS[2]) - decimal(BIGS[0]), decimal(BIGS[1]));
}

#[test]
//#[ignore]
fn test_mul() {
   for big in BIGS.iter() {
       assert_eq!(decimal(big) * decimal(&quot;2&quot;), decimal(big) + decimal(big));
   }
}

// test identities
#[test]
//#[ignore]
fn test_add_id() {
   assert_eq!(decimal(&quot;1.0&quot;) + decimal(&quot;0.0&quot;), decimal(&quot;1.0&quot;));
   assert_eq!(decimal(&quot;0.1&quot;) + decimal(&quot;0.0&quot;), decimal(&quot;0.1&quot;));
   assert_eq!(decimal(&quot;0.0&quot;) + decimal(&quot;1.0&quot;), decimal(&quot;1.0&quot;));
   assert_eq!(decimal(&quot;0.0&quot;) + decimal(&quot;0.1&quot;), decimal(&quot;0.1&quot;));
}

#[test]
//#[ignore]
fn test_sub_id() {
   assert_eq!(decimal(&quot;1.0&quot;) - decimal(&quot;0.0&quot;), decimal(&quot;1.0&quot;));
   assert_eq!(decimal(&quot;0.1&quot;) - decimal(&quot;0.0&quot;), decimal(&quot;0.1&quot;));
}

#[test]
//#[ignore]
fn test_mul_id() {
   assert_eq!(decimal(&quot;2.1&quot;) * decimal(&quot;1.0&quot;), decimal(&quot;2.1&quot;));
   assert_eq!(decimal(&quot;1.0&quot;) * decimal(&quot;2.1&quot;), decimal(&quot;2.1&quot;));
}

#[test]
//#[ignore]
fn test_gt_positive_and_zero() {
   assert!(decimal(&quot;1.0&quot;) &gt; decimal(&quot;0.0&quot;));
   assert!(decimal(&quot;0.1&quot;) &gt; decimal(&quot;0.0&quot;));
}

#[test]
//#[ignore]
fn test_gt_negative_and_zero() {
   assert!(decimal(&quot;0.0&quot;) &gt; decimal(&quot;-0.1&quot;));
   assert!(decimal(&quot;0.0&quot;) &gt; decimal(&quot;-1.0&quot;));
}

// tests of arbitrary precision behavior
#[test]
//#[ignore]
fn test_add_uneven_position() {
   assert_eq!(decimal(&quot;0.1&quot;) + decimal(&quot;0.02&quot;), decimal(&quot;0.12&quot;));
}

#[test]
//#[ignore]
fn test_eq_vary_sig_digits() {
   assert!(decimal(&quot;0&quot;) == decimal(&quot;0000000000000.0000000000000000000000&quot;));
   assert!(decimal(&quot;1&quot;) == decimal(&quot;00000000000000001.000000000000000000&quot;));
}

#[test]
//#[ignore]
fn test_add_vary_precision() {
   assert_eq!(
       decimal(&quot;100000000000000000000000000000000000000000000&quot;)
           + decimal(&quot;0.00000000000000000000000000000000000000001&quot;),
       decimal(BIGS[0])
   )
}

#[test]
//#[ignore]
fn test_cleanup_precision() {
   assert_eq!(
       decimal(&quot;10000000000000000000000000000000000000000000000.999999999999999999999999998&quot;,)
           + decimal(
               &quot;10000000000000000000000000000000000000000000000.000000000000000000000000002&quot;,
           ),
       decimal(&quot;20000000000000000000000000000000000000000000001&quot;)
   )
}

#[test]
//#[ignore]
fn test_gt_varying_positive_precisions() {
   assert!(decimal(&quot;1.1&quot;) &gt; decimal(&quot;1.01&quot;));
   assert!(decimal(&quot;1.01&quot;) &gt; decimal(&quot;1.0&quot;));
   assert!(decimal(&quot;1.0&quot;) &gt; decimal(&quot;0.1&quot;));
   assert!(decimal(&quot;0.1&quot;) &gt; decimal(&quot;0.01&quot;));
}

#[test]
//#[ignore]
fn test_gt_positive_and_negative() {
   assert!(decimal(&quot;1.0&quot;) &gt; decimal(&quot;-1.0&quot;));
   assert!(decimal(&quot;1.1&quot;) &gt; decimal(&quot;-1.1&quot;));
   assert!(decimal(&quot;0.1&quot;) &gt; decimal(&quot;-0.1&quot;));
}

#[test]
//#[ignore]
fn test_gt_varying_negative_precisions() {
   assert!(decimal(&quot;-0.01&quot;) &gt; decimal(&quot;-0.1&quot;));
   assert!(decimal(&quot;-0.1&quot;) &gt; decimal(&quot;-1.0&quot;));
   assert!(decimal(&quot;-1.0&quot;) &gt; decimal(&quot;-1.01&quot;));
   assert!(decimal(&quot;-1.01&quot;) &gt; decimal(&quot;-1.1&quot;));
}

// test signed properties
#[test]
//#[ignore]
fn test_negatives() {
   assert!(Decimal::try_from(&quot;-1&quot;).is_some());
   assert_eq!(decimal(&quot;0&quot;) - decimal(&quot;1&quot;), decimal(&quot;-1&quot;));
   assert_eq!(decimal(&quot;5.5&quot;) + decimal(&quot;-6.5&quot;), decimal(&quot;-1&quot;));
}

#[test]
//#[ignore]
fn test_explicit_positive() {
   assert_eq!(decimal(&quot;+1&quot;), decimal(&quot;1&quot;));
   assert_eq!(decimal(&quot;+2.0&quot;) - decimal(&quot;-0002.0&quot;), decimal(&quot;4&quot;));
}

#[test]
//#[ignore]
fn test_multiply_by_negative() {
   assert_eq!(decimal(&quot;5&quot;) * decimal(&quot;-0.2&quot;), decimal(&quot;-1&quot;));
   assert_eq!(decimal(&quot;-20&quot;) * decimal(&quot;-0.2&quot;), decimal(&quot;4&quot;));
}

#[test]
//#[ignore]
fn test_simple_partial_cmp() {
   assert!(decimal(&quot;1.0&quot;) &lt; decimal(&quot;1.1&quot;));
   assert!(decimal(&quot;0.00000000000000000000001&quot;) &gt; decimal(&quot;-20000000000000000000000000000&quot;));
}

// test carrying rules
// these tests are designed to ensure correctness of implementations for which the
// integer and fractional parts of the number are stored separately
#[test]
//#[ignore]
fn test_carry_into_integer() {
   assert_eq!(decimal(&quot;0.901&quot;) + decimal(&quot;0.1&quot;), decimal(&quot;1.001&quot;))
}

#[test]
//#[ignore]
fn test_carry_into_fractional_with_digits_to_right() {
   assert_eq!(decimal(&quot;0.0901&quot;) + decimal(&quot;0.01&quot;), decimal(&quot;0.1001&quot;))
}

#[test]
//#[ignore]
fn test_add_carry_over_negative() {
   assert_eq!(decimal(&quot;-1.99&quot;) + decimal(&quot;-0.01&quot;), decimal(&quot;-2.0&quot;))
}

#[test]
//#[ignore]
fn test_sub_carry_over_negative() {
   assert_eq!(decimal(&quot;-1.99&quot;) - decimal(&quot;0.01&quot;), decimal(&quot;-2.0&quot;))
}

#[test]
//#[ignore]
fn test_add_carry_over_negative_with_fractional() {
   assert_eq!(decimal(&quot;-1.99&quot;) + decimal(&quot;-0.02&quot;), decimal(&quot;-2.01&quot;))
}

#[test]
//#[ignore]
fn test_sub_carry_over_negative_with_fractional() {
   assert_eq!(decimal(&quot;-1.99&quot;) - decimal(&quot;0.02&quot;), decimal(&quot;-2.01&quot;))
}

#[test]
//#[ignore]
fn test_carry_from_rightmost_one() {
   assert_eq!(decimal(&quot;0.09&quot;) + decimal(&quot;0.01&quot;), decimal(&quot;0.1&quot;))
}

#[test]
//#[ignore]
fn test_carry_from_rightmost_more() {
   assert_eq!(decimal(&quot;0.099&quot;) + decimal(&quot;0.001&quot;), decimal(&quot;0.1&quot;))
}

#[test]
//#[ignore]
fn test_carry_from_rightmost_into_integer() {
   assert_eq!(decimal(&quot;0.999&quot;) + decimal(&quot;0.001&quot;), decimal(&quot;1.0&quot;))
}

// test arithmetic borrow rules
#[test]
//#[ignore]
fn test_add_borrow() {
   assert_eq!(decimal(&quot;0.01&quot;) + decimal(&quot;-0.0001&quot;), decimal(&quot;0.0099&quot;))
}

#[test]
//#[ignore]
fn test_sub_borrow() {
   assert_eq!(decimal(&quot;0.01&quot;) - decimal(&quot;0.0001&quot;), decimal(&quot;0.0099&quot;))
}

#[test]
//#[ignore]
fn test_add_borrow_integral() {
   assert_eq!(decimal(&quot;1.0&quot;) + decimal(&quot;-0.01&quot;), decimal(&quot;0.99&quot;))
}

#[test]
//#[ignore]
fn test_sub_borrow_integral() {
   assert_eq!(decimal(&quot;1.0&quot;) - decimal(&quot;0.01&quot;), decimal(&quot;0.99&quot;))
}

#[test]
//#[ignore]
fn test_add_borrow_integral_zeroes() {
   assert_eq!(decimal(&quot;1.0&quot;) + decimal(&quot;-0.99&quot;), decimal(&quot;0.01&quot;))
}

#[test]
//#[ignore]
fn test_sub_borrow_integral_zeroes() {
   assert_eq!(decimal(&quot;1.0&quot;) - decimal(&quot;0.99&quot;), decimal(&quot;0.01&quot;))
}

#[test]
//#[ignore]
fn test_borrow_from_negative() {
   assert_eq!(decimal(&quot;-1.0&quot;) + decimal(&quot;0.01&quot;), decimal(&quot;-0.99&quot;))
}

#[test]
//#[ignore]
fn test_add_into_fewer_digits() {
   assert_eq!(decimal(&quot;0.011&quot;) + decimal(&quot;-0.001&quot;), decimal(&quot;0.01&quot;))
}

// misc tests of arithmetic properties
#[test]
//#[ignore]
fn test_sub_into_fewer_digits() {
   assert_eq!(decimal(&quot;0.011&quot;) - decimal(&quot;0.001&quot;), decimal(&quot;0.01&quot;))
}

#[test]
//#[ignore]
fn test_add_away_decimal() {
   assert_eq!(decimal(&quot;1.1&quot;) + decimal(&quot;-0.1&quot;), decimal(&quot;1.0&quot;))
}

#[test]
//#[ignore]
fn test_sub_away_decimal() {
   assert_eq!(decimal(&quot;1.1&quot;) - decimal(&quot;0.1&quot;), decimal(&quot;1.0&quot;))
}

#}</code></pre></pre>
<a class="header" href="#4-答案-75" id="4-答案-75"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::cmp::Ordering;
use std::fmt;
use std::ops::{Add, Mul, Sub};

#[macro_use]
extern crate try_opt;

extern crate num_bigint;
use num_bigint::BigInt;
extern crate num_traits;
use num_traits::pow;

/// Type implementing arbitrary-precision decimal arithmetic
#[derive(Debug, Eq, Clone)]
pub struct Decimal {
   digits: BigInt,
   decimal_index: usize,
}

impl Decimal {
   fn new(digits: BigInt, decimal_index: usize) -&gt; Decimal {
       let mut value = Decimal {
           digits: digits,
           decimal_index: decimal_index,
       };
       value.reduce();
       value
   }

   pub fn try_from(mut input: &amp;str) -&gt; Option&lt;Decimal&gt; {
       // clear extraneous whitespace
       input = input.trim();

       // don't bother to trim extraneous zeroes
       // leave it to users to manage their own memory

       // now build a representation of the number to parse
       let mut digits = String::with_capacity(input.len());
       let mut decimal_index = None;
       for ch in input.chars() {
           match ch {
               '0'...'9' | '-' | '+' =&gt; {
                   digits.push(ch);
                   if let Some(idx) = decimal_index.as_mut() {
                       *idx += 1;
                   }
               }
               '.' =&gt; {
                   if decimal_index.is_some() {
                       return None;
                   }
                   decimal_index = Some(0)
               }
               _ =&gt; return None,
           }
       }
       Some(Decimal::new(
           try_opt!(digits.parse::&lt;BigInt&gt;().ok()),
           match decimal_index {
               Some(idx) =&gt; idx,
               None =&gt; 0,
           },
       ))
   }

   /// Add precision to the less-precise value until precisions match
   ///
   /// Precision, in this case, is defined as the decimal index.
   fn equalize_precision(mut one: &amp;mut Decimal, mut two: &amp;mut Decimal) {
       fn expand(lower_precision: &amp;mut Decimal, higher_precision: &amp;Decimal) {
           let precision_difference =
               (higher_precision.decimal_index - lower_precision.decimal_index) as usize;

           lower_precision.digits =
               &amp;lower_precision.digits * pow(BigInt::from(10_usize), precision_difference);
           lower_precision.decimal_index += precision_difference;
       }
       if one.decimal_index &lt; two.decimal_index {
           expand(&amp;mut one, &amp;two)
       } else if one.decimal_index &gt; two.decimal_index {
           expand(&amp;mut two, &amp;one)
       }
       assert_eq!(one.decimal_index, two.decimal_index);
   }

   /// Eliminate extraneous trailing zeroes
   ///
   /// This reduces the decimal index, so that the raw values are easier to parse
   fn reduce(&amp;mut self) {
       let extra_zeroes = self.digits
           .to_string() // produce a decimal representation
           .chars()
           .rev() // trailing values
           .take(self.decimal_index) // not counting past the decimal point
           .take_while(|&amp;c| c == '0') // counting only `0` digits
           .count();
       self.digits = &amp;self.digits / pow(BigInt::from(10_usize), extra_zeroes);
       self.decimal_index -= extra_zeroes;
   }
}

macro_rules! auto_impl_decimal_ops {
   ($trait:ident, $func_name:ident, $digits_operation:expr, $index_operation:expr) =&gt; {
       impl $trait for Decimal {
           type Output = Self;
           fn $func_name(mut self, mut rhs: Self) -&gt; Self {
               Decimal::equalize_precision(&amp;mut self, &amp;mut rhs);
               Decimal::new(
                   $digits_operation(self.digits, rhs.digits),
                   $index_operation(self.decimal_index, rhs.decimal_index),
               )
           }
       }
   };
}

auto_impl_decimal_ops!(Add, add, |s, o| s + o, |s, _| s);
auto_impl_decimal_ops!(Sub, sub, |s, o| s - o, |s, _| s);
auto_impl_decimal_ops!(Mul, mul, |s, o| s * o, |s, o| s + o);

macro_rules! auto_impl_decimal_cow {
   ($trait:ident, $func_name:ident, $digits_operation:expr, $return_type:ty) =&gt; {
       impl $trait for Decimal {
           fn $func_name(&amp;self, other: &amp;Self) -&gt; $return_type {
               if self.decimal_index == other.decimal_index {
                   $digits_operation(&amp;self.digits, &amp;other.digits)
               } else {
                   // if we're here, the decimal indexes are unmatched.
                   // We have to compare equal terms.
                   // clone both sides so we can modify either of them as necessary.
                   // not efficient, but whatever.
                   let mut one = self.clone();
                   let mut two = other.clone();
                   Decimal::equalize_precision(&amp;mut one, &amp;mut two);
                   one.$func_name(&amp;two)
               }
           }
       }
   };
}

auto_impl_decimal_cow!(PartialEq, eq, |a, b| a == b, bool);
auto_impl_decimal_cow!(Ord, cmp, |a: &amp;BigInt, b: &amp;BigInt| a.cmp(b), Ordering);

impl PartialOrd for Decimal {
   fn partial_cmp(&amp;self, other: &amp;Decimal) -&gt; Option&lt;Ordering&gt; {
       Some(self.cmp(other))
   }
}

impl fmt::Display for Decimal {
   fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
       // get a representation of the pure digits,
       // left-padded with zeroes
       let digits = format!(&quot;{:0&gt;width$}&quot;, self.digits, width = self.decimal_index);
       if self.decimal_index == digits.len() {
           write!(f, &quot;0.{}&quot;, digits)
       } else if self.decimal_index == 0 {
           write!(f, &quot;{}&quot;, digits)
       } else {
           let (before_index, after_index) = digits.split_at(digits.len() - self.decimal_index);
           write!(f, &quot;{}.{}&quot;, before_index, after_index)
       }
   }
}

#[cfg(test)]
mod tests {
   use super::*;

   #[test]
   fn test_display_temp() {
       for test_str in vec![&quot;0&quot;, &quot;1&quot;, &quot;20&quot;, &quot;0.3&quot;, &quot;0.04&quot;, &quot;50.05&quot;, &quot;66.0006&quot;, &quot;0.007&quot;] {
           println!(
               &quot;Decimal representation of \&quot;{}\&quot;: {}&quot;,
               test_str,
               Decimal::try_from(test_str).expect(&quot;This should always become a decimal&quot;)
           );
           assert_eq!(
               test_str,
               Decimal::try_from(test_str)
                   .expect(&quot;This should always become a decimal&quot;)
                   .to_string()
           )
       }
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-75" id="填充相关-75"><h2>填充/相关</h2></a>
<a class="header" href="#anagram" id="anagram"><h1>Anagram</h1></a>
<a class="header" href="#1-readme-76" id="1-readme-76"><h2>1. Readme</h2></a>
<a class="header" href="#字谜" id="字谜"><h1>字谜</h1></a>
<p>给出一个单词和可能的字谜列表，选择正确的子列表.</p>
<p>给出<code>&quot;listen&quot;</code>和候选人名单一样<code>&quot;enlists&quot; &quot;google&quot; &quot;inlets&quot; &quot;banana&quot;</code>程序应该返回一个包含<code>&quot;inlets&quot;</code>的列表。</p>
<a class="header" href="#资源-59" id="资源-59"><h2>资源</h2></a>
<p>受到 Extreme Startup 游戏的启发<a href="https://github.com/rchatley/extreme_startup">https://github.com/rchatley/extreme_startup</a></p>
<a class="header" href="#2-开始你的表演-76" id="2-开始你的表演-76"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::collections::HashSet;

pub fn anagrams_for&lt;'a&gt;(word: &amp;str, possible_anagrams: &amp;[&amp;str]) -&gt; HashSet&lt;&amp;'a str&gt; {
   unimplemented!(
       &quot;For the '{}' word find anagrams among the following words: {:?}&quot;,
       word,
       possible_anagrams
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-76" id="3-测试代码查看-76"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// use std::collections::HashSet;
use std::iter::FromIterator;

fn process_anagram_case(word: &amp;str, inputs: &amp;[&amp;str], expected: &amp;[&amp;str]) {
   let result = anagrams_for(word, inputs);

   let expected: HashSet&lt;&amp;str&gt; = HashSet::from_iter(expected.iter().cloned());

   assert_eq!(result, expected);
}

#[test]
fn test_no_matches() {
   let word = &quot;diaper&quot;;

   let inputs = [&quot;hello&quot;, &quot;world&quot;, &quot;zombies&quot;, &quot;pants&quot;];

   let outputs = vec![];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_detect_simple_anagram() {
   let word = &quot;ant&quot;;

   let inputs = [&quot;tan&quot;, &quot;stand&quot;, &quot;at&quot;];

   let outputs = vec![&quot;tan&quot;];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_does_not_confuse_different_duplicates() {
   let word = &quot;galea&quot;;

   let inputs = [&quot;eagle&quot;];

   let outputs = vec![];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_eliminate_anagram_subsets() {
   let word = &quot;good&quot;;

   let inputs = [&quot;dog&quot;, &quot;goody&quot;];

   let outputs = vec![];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_detect_anagram() {
   let word = &quot;listen&quot;;

   let inputs = [&quot;enlists&quot;, &quot;google&quot;, &quot;inlets&quot;, &quot;banana&quot;];

   let outputs = vec![&quot;inlets&quot;];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_multiple_anagrams() {
   let word = &quot;allergy&quot;;

   let inputs = [
       &quot;gallery&quot;,
       &quot;ballerina&quot;,
       &quot;regally&quot;,
       &quot;clergy&quot;,
       &quot;largely&quot;,
       &quot;leading&quot;,
   ];

   let outputs = vec![&quot;gallery&quot;, &quot;regally&quot;, &quot;largely&quot;];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_case_insensitive_anagrams() {
   let word = &quot;Orchestra&quot;;

   let inputs = [&quot;cashregister&quot;, &quot;Carthorse&quot;, &quot;radishes&quot;];

   let outputs = vec![&quot;Carthorse&quot;];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_unicode_anagrams() {
   let word = &quot;ΑΒΓ&quot;;

   // These words don't make sense, they're just greek letters cobbled together.
   let inputs = [&quot;ΒΓΑ&quot;, &quot;ΒΓΔ&quot;, &quot;γβα&quot;];

   let outputs = vec![&quot;ΒΓΑ&quot;, &quot;γβα&quot;];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_misleading_unicode_anagrams() {
   // Despite what a human might think these words different letters, the input uses Greek A and B
   // while the list of potential anagrams uses Latin A and B.
   let word = &quot;ΑΒΓ&quot;;

   let inputs = [&quot;ABΓ&quot;];

   let outputs = vec![];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_does_not_detect_a_word_as_its_own_anagram() {
   let word = &quot;banana&quot;;

   let inputs = [&quot;banana&quot;];

   let outputs = vec![];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_does_not_detect_a_differently_cased_word_as_its_own_anagram() {
   let word = &quot;banana&quot;;

   let inputs = [&quot;bAnana&quot;];

   let outputs = vec![];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_does_not_detect_a_differently_cased_unicode_word_as_its_own_anagram() {
   let word = &quot;ΑΒΓ&quot;;

   let inputs = [&quot;ΑΒγ&quot;];

   let outputs = vec![];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#[test]
//#[ignore]
fn test_same_bytes_different_chars() {
   let word = &quot;a⬂&quot;; // 61 E2 AC 82

   let inputs = [&quot;€a&quot;]; // E2 82 AC 61

   let outputs = vec![];

   process_anagram_case(word, &amp;inputs, &amp;outputs);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-76" id="4-答案-76"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashSet;

fn sort(word: &amp;String) -&gt; String {
   let mut sorted: Vec&lt;char&gt; = word.chars().collect();
   sorted.sort();
   sorted.into_iter().collect()
}

pub fn anagrams_for&lt;'a&gt;(word: &amp;str, inputs: &amp;[&amp;'a str]) -&gt; HashSet&lt;&amp;'a str&gt; {
   let lower = word.to_lowercase();
   let sorted = sort(&amp;lower);
   inputs
       .iter()
       .filter(|input| {
           let input_lower = input.to_lowercase();
           lower != input_lower &amp;&amp; sorted == sort(&amp;input_lower)
       })
       .cloned()
       .collect()
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-76" id="填充相关-76"><h2>填充/相关</h2></a>
<a class="header" href="#protein-translation" id="protein-translation"><h1>Protein Translation</h1></a>
<a class="header" href="#1-readme-77" id="1-readme-77"><h2>1. Readme</h2></a>
<a class="header" href="#蛋白质转译" id="蛋白质转译"><h1>蛋白质转译</h1></a>
<p>将 RNA 序列转译成蛋白质.</p>
<p>RNA 可以分解为三个称为密码子的核苷酸序列，然后转译成多肽，如下:</p>
<p>RNA:<code>&quot;AUGUUUUCU&quot;</code>=&gt;转译成</p>
<p>密码子:<code>&quot;AUG&quot;， &quot;UUU&quot;， &quot;UCU&quot;</code>=&gt;其成为具有以下序列的多肽=&gt;</p>
<p>蛋白:<code>&quot;Methionine&quot;， &quot;Phenylalanine&quot;， &quot;Serine&quot;</code></p>
<p>这有 64 个密码子，而这些密码子又相当于 20 个氨基酸；然而，在本练习中，所有密码子序列和所得氨基酸都不重要。如果它适用于一个密码子，该程序应该适用于所有这些密码子。但是，您可以随意扩展测试套件中的列表以包含它们.</p>
<p>还有三个终止密码子(也称为’STOP’密码子)；如果遇到任何这些密码子(通过核糖体)，那么所有转译结束，并终止蛋白质。</p>
<p>之后的所有后续密码子都会被忽略，如下所示:</p>
<p>RNA:<code>&quot;AUGUUUUCUUAAAUG&quot;</code>=&gt;</p>
<p>密码:<code>&quot;AUG&quot;， &quot;UUU&quot;， &quot;UCU&quot;， &quot;UAA&quot;， &quot;AUG&quot;</code>=&gt;</p>
<p>蛋白:<code>&quot;Methionine&quot;， &quot;Phenylalanine&quot;， &quot;Serine&quot;</code></p>
<p>注意终止密码子<code>&quot;UAA&quot;</code>终止转译，最终的蛋氨酸，不会转译成蛋白质序列。</p>
<p>以下是本练习所需的密码子和产生的氨基酸。</p>
<table><thead><tr><th align="left"> 密码子             </th><th align="left"> 蛋白     </th></tr></thead><tbody>
<tr><td align="left"> AUG                </td><td align="left"> 蛋氨酸   </td></tr>
<tr><td align="left"> UUU，UUC           </td><td align="left"> 苯丙氨酸 </td></tr>
<tr><td align="left"> UUA，UUG           </td><td align="left"> 亮氨酸   </td></tr>
<tr><td align="left"> UCU，UCC，UCA，UCG </td><td align="left"> 丝氨酸   </td></tr>
<tr><td align="left"> UAU，UAC           </td><td align="left"> 酪氨酸   </td></tr>
<tr><td align="left"> UGU，UGC           </td><td align="left"> 半胱氨酸 </td></tr>
<tr><td align="left"> UGG                </td><td align="left"> 色氨酸   </td></tr>
<tr><td align="left"> UAA，UAG，UGA      </td><td align="left"> STOP     </td></tr>
</tbody></table>
<p>学习更多关于<a href="http://en.wikipedia.org/wiki/Translation_(biology)">蛋白质转译：维基百科</a></p>
<a class="header" href="#资源-60" id="资源-60"><h2>资源</h2></a>
<p>Tyler Long</p>
<a class="header" href="#2-开始你的表演-77" id="2-开始你的表演-77"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::marker::PhantomData;

pub struct CodonsInfo&lt;'a&gt; {
   // This field is here to make the template compile and not to
   // complain about unused type lifetime parameter &quot;'a&quot;. Once you start
   // solving the exercise, delete this field and the 'std::marker::PhantomData'
   // import.
   phantom: PhantomData&lt;&amp;'a ()&gt;,
}

impl&lt;'a&gt; CodonsInfo&lt;'a&gt; {
   pub fn name_for(&amp;self, codon: &amp;str) -&gt; Option&lt;&amp;'a str&gt; {
       unimplemented!(
           &quot;Return the protein name for a '{}' codon or None, if codon string is invalid&quot;,
           codon
       );
   }

   pub fn of_rna(&amp;self, rna: &amp;str) -&gt; Option&lt;Vec&lt;&amp;'a str&gt;&gt; {
       unimplemented!(&quot;Return a list of protein names that correspond to the '{}' RNA string or None if the RNA string is invalid&quot;, rna);
   }
}

pub fn parse&lt;'a&gt;(pairs: Vec&lt;(&amp;'a str, &amp;'a str)&gt;) -&gt; CodonsInfo&lt;'a&gt; {
   unimplemented!(
       &quot;Construct a new CodonsInfo struct from given pairs: {:?}&quot;,
       pairs
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-77" id="3-测试代码查看-77"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_methionine() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;AUG&quot;), Some(&quot;methionine&quot;));
}

#[test]
//#[ignore]
fn test_cysteine_tgt() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;UGU&quot;), Some(&quot;cysteine&quot;));
}

#[test]
//#[ignore]
fn test_stop() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;UAA&quot;), Some(&quot;stop codon&quot;));
}

#[test]
//#[ignore]
fn test_valine() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;GUU&quot;), Some(&quot;valine&quot;));
}

#[test]
//#[ignore]
fn test_isoleucine() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;AUU&quot;), Some(&quot;isoleucine&quot;));
}

#[test]
//#[ignore]
fn test_arginine_name() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;CGA&quot;), Some(&quot;arginine&quot;));
   assert_eq!(info.name_for(&quot;AGA&quot;), Some(&quot;arginine&quot;));
   assert_eq!(info.name_for(&quot;AGG&quot;), Some(&quot;arginine&quot;));
}

#[test]
//#[ignore]
fn empty_is_invalid() {
   let info = parse(make_pairs());
   assert!(info.name_for(&quot;&quot;).is_none());
}

#[test]
//#[ignore]
fn x_is_not_shorthand_so_is_invalid() {
   let info = parse(make_pairs());
   assert!(info.name_for(&quot;VWX&quot;).is_none());
}

#[test]
//#[ignore]
fn too_short_is_invalid() {
   let info = parse(make_pairs());
   assert!(info.name_for(&quot;AU&quot;).is_none());
}

#[test]
//#[ignore]
fn too_long_is_invalid() {
   let info = parse(make_pairs());
   assert!(info.name_for(&quot;ATTA&quot;).is_none());
}

#[test]
//#[ignore]
fn test_translates_rna_strand_into_correct_protein() {
   let info = parse(make_pairs());
   assert_eq!(
       info.of_rna(&quot;AUGUUUUGG&quot;),
       Some(vec![&quot;methionine&quot;, &quot;phenylalanine&quot;, &quot;tryptophan&quot;])
   );
}

#[test]
//#[ignore]
fn test_stops_translation_if_stop_codon_present() {
   let info = parse(make_pairs());
   assert_eq!(
       info.of_rna(&quot;AUGUUUUAA&quot;),
       Some(vec![&quot;methionine&quot;, &quot;phenylalanine&quot;])
   );
}

#[test]
//#[ignore]
fn test_stops_translation_of_longer_strand() {
   let info = parse(make_pairs());
   assert_eq!(
       info.of_rna(&quot;UGGUGUUAUUAAUGGUUU&quot;),
       Some(vec![&quot;tryptophan&quot;, &quot;cysteine&quot;, &quot;tyrosine&quot;])
   );
}

#[test]
//#[ignore]
fn test_invalid_codons() {
   let info = parse(make_pairs());
   assert!(info.of_rna(&quot;CARROT&quot;).is_none());
}

// The input data constructor. Returns a list of codon, name pairs.
fn make_pairs() -&gt; Vec&lt;(&amp;'static str, &amp;'static str)&gt; {
   let grouped = vec![
       (&quot;isoleucine&quot;, vec![&quot;AUU&quot;, &quot;AUC&quot;, &quot;AUA&quot;]),
       (&quot;valine&quot;, vec![&quot;GUU&quot;, &quot;GUC&quot;, &quot;GUA&quot;, &quot;GUG&quot;]),
       (&quot;phenylalanine&quot;, vec![&quot;UUU&quot;, &quot;UUC&quot;]),
       (&quot;methionine&quot;, vec![&quot;AUG&quot;]),
       (&quot;cysteine&quot;, vec![&quot;UGU&quot;, &quot;UGC&quot;]),
       (&quot;alanine&quot;, vec![&quot;GCU&quot;, &quot;GCC&quot;, &quot;GCA&quot;, &quot;GCG&quot;]),
       (&quot;glycine&quot;, vec![&quot;GGU&quot;, &quot;GGC&quot;, &quot;GGA&quot;, &quot;GGG&quot;]),
       (&quot;proline&quot;, vec![&quot;CCU&quot;, &quot;CCC&quot;, &quot;CCA&quot;, &quot;CCG&quot;]),
       (&quot;threonine&quot;, vec![&quot;ACU&quot;, &quot;ACC&quot;, &quot;ACA&quot;, &quot;ACG&quot;]),
       (&quot;serine&quot;, vec![&quot;AGU&quot;, &quot;AGC&quot;]),
       (&quot;tyrosine&quot;, vec![&quot;UAU&quot;, &quot;UAC&quot;]),
       (&quot;tryptophan&quot;, vec![&quot;UGG&quot;]),
       (&quot;glutamine&quot;, vec![&quot;CAA&quot;, &quot;CAG&quot;]),
       (&quot;asparagine&quot;, vec![&quot;AAU&quot;, &quot;AAC&quot;]),
       (&quot;histidine&quot;, vec![&quot;CAU&quot;, &quot;CAC&quot;]),
       (&quot;glutamic acid&quot;, vec![&quot;GAA&quot;, &quot;GAG&quot;]),
       (&quot;aspartic acid&quot;, vec![&quot;GAU&quot;, &quot;GAC&quot;]),
       (&quot;lysine&quot;, vec![&quot;AAA&quot;, &quot;AAG&quot;]),
       (&quot;arginine&quot;, vec![&quot;CGU&quot;, &quot;CGC&quot;, &quot;CGA&quot;, &quot;CGG&quot;, &quot;AGA&quot;, &quot;AGG&quot;]),
       (&quot;stop codon&quot;, vec![&quot;UAA&quot;, &quot;UAG&quot;, &quot;UGA&quot;]),
   ];
   let mut pairs = Vec::&lt;(&amp;'static str, &amp;'static str)&gt;::new();
   for (name, codons) in grouped.into_iter() {
       for codon in codons {
           pairs.push((codon, name));
       }
   }
   pairs.sort_by(|&amp;(_, a), &amp;(_, b)| a.cmp(b));
   return pairs;
}

#}</code></pre></pre>
<a class="header" href="#4-答案-77" id="4-答案-77"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;

pub struct CodonInfo&lt;'a&gt; {
   actual_codons: HashMap&lt;&amp;'a str, &amp;'a str&gt;,
}

pub fn parse&lt;'a&gt;(pairs: Vec&lt;(&amp;'a str, &amp;'a str)&gt;) -&gt; CodonInfo&lt;'a&gt; {
   CodonInfo {
       actual_codons: pairs.into_iter().collect(),
   }
}

impl&lt;'a&gt; CodonInfo&lt;'a&gt; {
   pub fn name_for(&amp;self, codon: &amp;str) -&gt; Option&lt;&amp;'a str&gt; {
       self.actual_codons.get(&amp;codon).map(|&amp;acid| acid)
   }

   pub fn of_rna(&amp;self, strand: &amp;str) -&gt; Option&lt;Vec&lt;&amp;'a str&gt;&gt; {
       strand
           .chars()
           .collect::&lt;Vec&lt;char&gt;&gt;()
           .chunks(3)
           .map(|chars| self.name_for(&amp;chars.iter().collect::&lt;String&gt;()))
           .take_while(|result| result.is_none() || result.unwrap() != &quot;stop codon&quot;)
           .collect()
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-77" id="填充相关-77"><h2>填充/相关</h2></a>
<a class="header" href="#robot-name" id="robot-name"><h1>Robot Name</h1></a>
<a class="header" href="#1-readme-78" id="1-readme-78"><h2>1. Readme</h2></a>
<a class="header" href="#机器人名称" id="机器人名称"><h1>机器人名称</h1></a>
<p>管理机器人工厂设置.</p>
<p>当机器人从工厂车间出来时，他们没有名字。</p>
<p>第一次启动时，会生成一个随机名称，格式为两个大写字母后跟三个数字，如 RX837 或 BC811。</p>
<p>每隔一段时间我们就需要将机器人重置为出厂设置，这意味着他们的名字会被擦除。下次你问，它会以一个新的随机名称回复。</p>
<p>名称必须是随机的:它们不应遵循可预测的顺序。随机名称表示发生碰撞的风险。您的解决方案必须确保每个现有机器人都具有唯一名称。</p>
<a class="header" href="#资源-61" id="资源-61"><h2>资源</h2></a>
<p>与 Paul Blackwell 在 gSchool 的调试会议.<a href="http://gschool.it">http://gschool.it</a></p>
<a class="header" href="#2-开始你的表演-78" id="2-开始你的表演-78"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub struct Robot;

impl Robot {
   pub fn new() -&gt; Self {
       unimplemented!(&quot;Construct a new Robot struct.&quot;);
   }

   pub fn name(&amp;self) -&gt; &amp;str {
       unimplemented!(&quot;Return the reference to the robot's name.&quot;);
   }

   pub fn reset_name(&amp;mut self) {
       unimplemented!(&quot;Assign a new unique name to the robot.&quot;);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-78" id="3-测试代码查看-78"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn assert_name_matches_pattern(n: &amp;str) {
   assert!(n.len() == 5, &quot;name is exactly 5 characters long&quot;);
   assert!(
       n[0..2].chars().all(|c| c &gt;= 'A' &amp;&amp; c &lt;= 'Z'),
       &quot;name starts with 2 uppercase letters&quot;
   );
   assert!(
       n[2..].chars().all(|c| c &gt;= '0' &amp;&amp; c &lt;= '9'),
       &quot;name ends with 3 numbers&quot;
   );
}

fn assert_name_is_persistent(r: &amp;Robot) {
   // The type system already proves this, but why not.
   let n1 = r.name();
   let n2 = r.name();
   let n3 = r.name();
   assert_eq!(n1, n2);
   assert_eq!(n2, n3);
}

#[test]
fn test_name_should_match_expected_pattern() {
   let r = Robot::new();
   assert_name_matches_pattern(r.name());
}

#[test]
//#[ignore]
fn test_name_is_persistent() {
   assert_name_is_persistent(&amp;Robot::new());
}

#[test]
//#[ignore]
fn test_different_robots_have_different_names() {
   let r1 = Robot::new();
   let r2 = Robot::new();
   assert_ne!(r1.name(), r2.name(), &quot;Robot names should be different&quot;);
}

#[test]
//#[ignore]
fn test_new_name_should_match_expected_pattern() {
   let mut r = Robot::new();
   assert_name_matches_pattern(r.name());
   r.reset_name();
   assert_name_matches_pattern(r.name());
}

#[test]
//#[ignore]
fn test_new_name_is_persistent() {
   let mut r = Robot::new();
   r.reset_name();
   assert_name_is_persistent(&amp;r);
}

#[test]
//#[ignore]
fn test_new_name_is_different_from_old_name() {
   let mut r = Robot::new();
   let n1 = r.name().to_string();
   r.reset_name();
   let n2 = r.name().to_string();
   assert_ne!(n1, n2, &quot;Robot name should change when reset&quot;);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-78" id="4-答案-78"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
extern crate rand;
use rand::{thread_rng, Rng};

pub struct Robot {
   name: String,
}

fn generate_name() -&gt; String {
   let mut s = String::with_capacity(5);
   static LETTERS: &amp;'static [u8] = b&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;
   static NUMBERS: &amp;'static [u8] = b&quot;0123456789&quot;;
   for _ in 0..2 {
       s.push(thread_rng().choose(LETTERS).unwrap().clone() as char);
   }
   for _ in 0..3 {
       s.push(thread_rng().choose(NUMBERS).unwrap().clone() as char);
   }
   s
}

impl Robot {
   pub fn new() -&gt; Robot {
       Robot {
           name: generate_name(),
       }
   }

   pub fn name&lt;'a&gt;(&amp;'a self) -&gt; &amp;'a str {
       &amp;self.name[..]
   }

   pub fn reset_name(&amp;mut self) {
       self.name = generate_name();
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-78" id="填充相关-78"><h2>填充/相关</h2></a>
<a class="header" href="#book-store" id="book-store"><h1>Book Store</h1></a>
<a class="header" href="#1-readme-79" id="1-readme-79"><h2>1. Readme</h2></a>
<a class="header" href="#书店" id="书店"><h1>书店</h1></a>
<p>为了尝试鼓励，畅销 5 书系列书籍的销售，书店决定提供多书购买的折扣。</p>
<p>这五本书中的任何一本都要花 8 美元.</p>
<p>但是，如果您购买两本不同的书籍，那么这两本书将获得 5%的折扣。</p>
<p>如果您购买 3 本不同的书籍，您将获得 10%的折扣。</p>
<p>如果您购买 4 本不同的书籍，您将获得 20%的折扣。</p>
<p>如果您全部购买 5 件，即可获得 25%的折扣。</p>
<p>注意：如果您购买了 4 本书，但不同的书只有 3 本，那么您可以在 3 本书中获得 10%的折扣，但是第 4 本书的价格仍为 8 美元。</p>
<p>你的任务是写一段代码，来计算购物车(这 5 本书的任意搭配)的价格(只包含同一系列的书籍)，给予尽可能大的折扣。</p>
<p>例如，购物车若是下面的书，那价格是多少?</p>
<ul>
<li>第一本书的 2 份</li>
<li>第二本书的 2 份</li>
<li>第三本书的 2 份</li>
<li>第四本书的 1 份</li>
<li>第五本书的 1 份</li>
</ul>
<p>将这 8 本书分组的一种方法是:</p>
<ul>
<li>第 1 组 5 本书 -&gt; 25%折扣(第 1，第 2，第 3，第 4，第 5)</li>
<li>还有 1 组 3 本书 -&gt; 10%折扣(第 1 名，第 2 名，第 3 名)</li>
</ul>
<p>这将总共给出:</p>
<ul>
<li>5 本书，25%的折扣</li>
<li>还有 3 本书可享受 10%的折扣</li>
</ul>
<p>导致:</p>
<ul>
<li>5 x(8 - 2.00)== 5 x 6.00 == $ 30.00</li>
<li>还有 3 x(8 - 0.80)== 3 x 7.20 == 21.60 美元</li>
</ul>
<p>总计 <strong>51.60</strong> 美元</p>
<p>但是，将这 8 本书分组的另一种方法是:</p>
<ul>
<li>第 1 组 4 本书 -&gt; 20%折扣(第 1，第 2，第 3，第 4)</li>
<li>还有 1 组 4 本书 -&gt; 20%折扣(第 1，第 2，第 3，第 5)</li>
</ul>
<p>这将总共给出:</p>
<ul>
<li>4 本书，20%的折扣</li>
<li>还有 4 本书，20%的折扣</li>
</ul>
<p>导致:</p>
<ul>
<li>4 x(8 - 1.60)== 4 x 6.40 == 25.60 美元</li>
<li>还有 4 x(8 - 1.60)== 4 x 6.40 == 25.60 美元</li>
</ul>
<p>总计 <strong>51.20</strong> 美元</p>
<p><strong>51.20</strong> 美元是最大折扣的价格.</p>
<a class="header" href="#资源-62" id="资源-62"><h2>资源</h2></a>
<p>灵感来自 Cyber​​-Dojo 的哈利波特卡塔.<a href="http://cyber-dojo.org">http://cyber-dojo.org</a></p>
<a class="header" href="#2-开始你的表演-79" id="2-开始你的表演-79"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn lowest_price(books: &amp;[u32]) -&gt; u32 {
   unimplemented!(
       &quot;Find the lowest price of the bookbasket with books {:?}&quot;,
       books
   )
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-79" id="3-测试代码查看-79"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// Tests for book-store
//
// Generated by [script][script] using [canonical data][canonical-data]
//
// [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py
// [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/book-store/canonical_data.json

/// Process a single test case for the property `total`
///
/// All cases for the `total` property are implemented
/// in terms of this function.
///
/// Expected input format: ('basket', 'targetgrouping')
fn process_total_case(input: (Vec&lt;u32&gt;, Vec&lt;Vec&lt;u32&gt;&gt;), expected: u32) {
   assert_eq!(lowest_price(&amp;input.0), expected)
}

// Return the total basket price after applying the best discount.
// Calculate lowest price for a shopping basket containing books only from
// a single series.  There is no discount advantage for having more than
// one copy of any single book in a grouping.

#[test]
/// Only a single book
fn test_only_a_single_book() {
   process_total_case((vec![1], vec![vec![1]]), 800);
}

#[test]
//#[ignore]
/// Two of the same book
fn test_two_of_the_same_book() {
   process_total_case((vec![2, 2], vec![vec![2], vec![2]]), 1_600);
}

#[test]
//#[ignore]
/// Empty basket
fn test_empty_basket() {
   process_total_case((vec![], vec![]), 0);
}

#[test]
//#[ignore]
/// Two different books
fn test_two_different_books() {
   process_total_case((vec![1, 2], vec![vec![1, 2]]), 1_520);
}

#[test]
//#[ignore]
/// Three different books
fn test_three_different_books() {
   process_total_case((vec![1, 2, 3], vec![vec![1, 2, 3]]), 2_160);
}

#[test]
//#[ignore]
/// Four different books
fn test_four_different_books() {
   process_total_case((vec![1, 2, 3, 4], vec![vec![1, 2, 3, 4]]), 2_560);
}

#[test]
//#[ignore]
/// Five different books
fn test_five_different_books() {
   process_total_case((vec![1, 2, 3, 4, 5], vec![vec![1, 2, 3, 4, 5]]), 3_000);
}

#[test]
//#[ignore]
/// Two groups of four is cheaper than group of five plus group of three
fn test_two_groups_of_four_is_cheaper_than_group_of_five_plus_group_of_three() {
   process_total_case(
       (
           vec![1, 1, 2, 2, 3, 3, 4, 5],
           vec![vec![1, 2, 3, 4], vec![1, 2, 3, 5]],
       ),
       5_120,
   );
}

#[test]
//#[ignore]
/// Group of four plus group of two is cheaper than two groups of three
fn test_group_of_four_plus_group_of_two_is_cheaper_than_two_groups_of_three() {
   process_total_case(
       (vec![1, 1, 2, 2, 3, 4], vec![vec![1, 2, 3, 4], vec![1, 2]]),
       4_080,
   );
}

#[test]
//#[ignore]
/// Two each of first 4 books and 1 copy each of rest
fn test_two_each_of_first_4_books_and_1_copy_each_of_rest() {
   process_total_case(
       (
           vec![1, 1, 2, 2, 3, 3, 4, 4, 5],
           vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4]],
       ),
       5_560,
   );
}

#[test]
//#[ignore]
/// Two copies of each book
fn test_two_copies_of_each_book() {
   process_total_case(
       (
           vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5],
           vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5]],
       ),
       6_000,
   );
}

#[test]
//#[ignore]
/// Three copies of first book and 2 each of remaining
fn test_three_copies_of_first_book_and_2_each_of_remaining() {
   process_total_case(
       (
           vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1],
           vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5], vec![1]],
       ),
       6_800,
   );
}

#[test]
//#[ignore]
/// Three each of first 2 books and 2 each of remaining books
fn test_three_each_of_first_2_books_and_2_each_of_remaining_books() {
   process_total_case(
       (
           vec![1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 1, 2],
           vec![vec![1, 2, 3, 4, 5], vec![1, 2, 3, 4, 5], vec![1, 2]],
       ),
       7_520,
   );
}

#[test]
//#[ignore]
/// Four groups of four are cheaper than two groups each of five and three
fn test_four_groups_of_four_are_cheaper_than_two_groups_each_of_five_and_three() {
   process_total_case(
       (
           vec![1, 1, 2, 2, 3, 3, 4, 5, 1, 1, 2, 2, 3, 3, 4, 5],
           vec![
               vec![1, 2, 3, 4],
               vec![1, 2, 3, 5],
               vec![1, 2, 3, 4],
               vec![1, 2, 3, 5],
           ],
       ),
       10_240,
   );
}

#}</code></pre></pre>
<a class="header" href="#4-答案-79" id="4-答案-79"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::hash_map::DefaultHasher;
use std::collections::{BTreeSet, HashSet};
use std::hash::{Hash, Hasher};
use std::mem;

type Book = u32;
type GroupedBasket = Vec&lt;Group&gt;;
type Price = u32;
const BOOK_PRICE: Price = 800;

#[derive(Debug, Clone, PartialEq, Eq)]
struct Group(RefCell&lt;BTreeSet&lt;Book&gt;&gt;);

impl Group {
   fn new() -&gt; Group {
       Group(RefCell::new(BTreeSet::new()))
   }

   fn new_containing(book: Book) -&gt; Group {
       let g = Group::new();
       g.0.borrow_mut().insert(book);
       g
   }

   fn price(&amp;self) -&gt; Price {
       (self.0.borrow().len() as Price) * BOOK_PRICE * match self.0.borrow().len() {
           2 =&gt; 95,
           3 =&gt; 90,
           4 =&gt; 80,
           5 =&gt; 75,
           _ =&gt; 100,
       } / 100
   }
}

impl Ord for Group {
   // we want to order groups first by qty contained DESC, then by lowest value ASC
   fn cmp(&amp;self, other: &amp;Group) -&gt; Ordering {
       match other.0.borrow().len().cmp(&amp;self.0.borrow().len()) {
           Ordering::Equal =&gt; {
               if self.0.borrow().len() == 0 {
                   Ordering::Equal
               } else {
                   self.0
                       .borrow()
                       .iter()
                       .next()
                       .unwrap()
                       .cmp(other.0.borrow().iter().next().unwrap())
               }
           }
           otherwise =&gt; otherwise,
       }
   }
}

impl PartialOrd for Group {
   fn partial_cmp(&amp;self, other: &amp;Group) -&gt; Option&lt;Ordering&gt; {
       Some(self.cmp(other))
   }
}

impl Hash for Group {
   fn hash&lt;H: Hasher&gt;(&amp;self, hasher: &amp;mut H) {
       self.0.borrow().hash(hasher);
   }
}

fn basket_price(basket: &amp;GroupedBasket) -&gt; Price {
   basket.iter().map(|g| g.price()).sum()
}

/// Compute the hash of a GroupedBasket
///
/// Note that we don't actually care at all about the _values_ within
/// the groups, only their lengths. Therefore, let's hash not the actual
/// GB but its lengths.
fn hash_of(basket: &amp;GroupedBasket) -&gt; u64 {
   let lengths = basket
       .iter()
       .map(|g| g.0.borrow().len())
       .collect::&lt;Vec&lt;_&gt;&gt;();
   let mut hasher = DefaultHasher::new();
   lengths.hash(&amp;mut hasher);
   hasher.finish()
}

pub fn lowest_price(books: &amp;[Book]) -&gt; Price {
   DecomposeGroups::new(books)
       .map(|gb| basket_price(&amp;gb))
       .min()
       .unwrap_or(0)
}

struct DecomposeGroups {
   prev_states: HashSet&lt;u64&gt;,
   next: Option&lt;GroupedBasket&gt;,
}

impl Iterator for DecomposeGroups {
   type Item = GroupedBasket;
   fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
       // our goal here: produce a stream of valid groups, differentiated by their
       // counts, from most compact to most dispersed.
       //
       // Algorithm:
       //  - Start with the most compact groups possible
       //  - If the number of groups == 0 or the max population of any group == 1, return None
       //  - For every item in the most populous group:
       //      - Try removing it and adding it to a smaller group.
       //          - Can any smaller group accept it? if yes, move it there and return
       //  - If it cannot be added to any smaller group, try the next item from this set
       //  - If no item from the most populous group can be added to any smaller group,
       //    then move the last item from the most populous group into a new group, alone,
       //    and return
       let return_value = self.next.clone();
       if let Some(groups) = mem::replace(&amp;mut self.next, None) {
           if !(groups.is_empty() || groups.iter().all(|g| g.0.borrow().len() == 1)) {
               let mut hypothetical;
               for mpg_book in groups[0].0.borrow().iter() {
                   for (idx, other_group) in groups[1..].iter().enumerate() {
                       if !other_group.0.borrow().contains(mpg_book) {
                           hypothetical = groups.clone();
                           hypothetical[0].0.borrow_mut().remove(mpg_book);
                           hypothetical[1 + idx].0.borrow_mut().insert(*mpg_book);
                           hypothetical.sort();
                           let hypothetical_hash = hash_of(&amp;hypothetical);
                           if !self.prev_states.contains(&amp;hypothetical_hash) {
                               self.prev_states.insert(hypothetical_hash);
                               mem::replace(&amp;mut self.next, Some(hypothetical));
                               return return_value;
                           }
                       }
                   }
               }
               // we've gone through all the items of the most populous group,
               // and none of them can be added to any other existing group.
               // We need to create a new group;
               let book = {
                   let backing_bt = groups[0].0.borrow();
                   let mut book_iter = backing_bt.iter();
                   book_iter.next().unwrap().clone()
               };
               hypothetical = groups.clone();
               hypothetical[0].0.borrow_mut().remove(&amp;book);
               hypothetical.push(Group::new_containing(book));
               hypothetical.sort();
               self.prev_states.insert(hash_of(&amp;hypothetical));
               mem::replace(&amp;mut self.next, Some(hypothetical));
           }
       }
       return_value
   }
}

impl DecomposeGroups {
   fn new(books: &amp;[Book]) -&gt; DecomposeGroups {
       let mut book_groups = GroupedBasket::new();
       'nextbook: for book in books {
           for idx in 0..book_groups.len() {
               if !book_groups[idx].0.borrow().contains(&amp;book) {
                   book_groups[idx].0.borrow_mut().insert(*book);
                   continue 'nextbook;
               }
           }
           // if we're here, we still haven't found a place for the book.
           // better add it to a new group
           book_groups.push(Group::new_containing(*book));
       }
       book_groups.sort();

       DecomposeGroups {
           next: Some(book_groups),
           prev_states: HashSet::new(),
       }
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-79" id="填充相关-79"><h2>填充/相关</h2></a>
<a class="header" href="#难" id="难"><h1>难</h1></a>
<ul>
<li><a href="./book-store/README.zh.html">Book Store</a></li>
<li><a href="./ocr-numbers/README.zh.html">OCR Numbers</a></li>
<li><a href="./minesweeper/README.zh.html">Minesweeper</a></li>
<li><a href="./dominoes/README.zh.html">Dominoes</a></li>
<li><a href="./parallel-letter-frequency/README.zh.html">Parallel Letter Frequency</a></li>
<li><a href="./rectangles/README.zh.html">Rectangles</a></li>
<li><a href="./forth/README.zh.html">Forth</a></li>
<li><a href="./circular-buffer/README.zh.html">Circular Buffer</a></li>
<li><a href="./react/README.zh.html">React</a></li>
</ul>
<a class="header" href="#ocr-numbers" id="ocr-numbers"><h1>OCR Numbers</h1></a>
<a class="header" href="#1-readme-80" id="1-readme-80"><h2>1. Readme</h2></a>
<a class="header" href="#ocr-号码" id="ocr-号码"><h1>OCR 号码</h1></a>
<p>给定一个 3 x 4 ，由竖线符号，下划线和空格组成的网格，确定代表哪个数字，或者是否是乱码。</p>
<a class="header" href="#第一步" id="第一步"><h1>第一步</h1></a>
<p>首先，将简单的二进制字体，转换为包含 0 或 1 的字符串。</p>
<p>二进制字体使用竖线符号和下划线，四行高，三列宽.</p>
<pre><code class="language-text">     _   #
    | |  # zero.
    |_|  #
         # 第 4 行总空着
</code></pre>
<p>转换为”0”</p>
<pre><code class="language-text">         #
      |  # one.
      |  #
         # (4行空)
</code></pre>
<p>转换为”1”</p>
<p>如果输入的大小正确，但无法识别，则程序应返回”?”</p>
<p>如果输入的大小不正确，程序应该返回错误。</p>
<a class="header" href="#第二步" id="第二步"><h1>第二步</h1></a>
<p>更新您的程序以识别多二进制字符串，用 ? 替换乱码。</p>
<a class="header" href="#第三步" id="第三步"><h1>第三步</h1></a>
<p>更新程序，以识别所有数字 0 到 9，既可以单独识别，也可以作为更大字符串的一部分识别。</p>
<pre><code class="language-text"> _
 _|
|_
</code></pre>
<p>转换为”2”</p>
<pre><code class="language-text">      _  _     _  _  _  _  _  _  #
    | _| _||_||_ |_   ||_||_|| | # 十进制数.
    ||_  _|  | _||_|  ||_| _||_| #
                                 # 第 4 行空着
</code></pre>
<p>被转换为”1234567890”</p>
<a class="header" href="#第四步" id="第四步"><h1>第四步</h1></a>
<p>更新程序以处理多个数字，每 4 行。转换多行时，请使用逗号连接行.</p>
<pre><code class="language-text">    _  _
  | _| _|
  ||_  _|

    _  _
|_||_ |_
  | _||_|

 _  _  _
  ||_||_|
  ||_| _|
</code></pre>
<p>被转换为”123，456，789”</p>
<a class="header" href="#资源-63" id="资源-63"><h2>资源</h2></a>
<p>灵感来自银行 OCR kata<a href="http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR">http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR</a></p>
<a class="header" href="#2-开始你的表演-80" id="2-开始你的表演-80"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">// The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.

#[derive(Debug, PartialEq)]
pub enum Error {
   InvalidRowCount(usize),
   InvalidColumnCount(usize),
}

pub fn convert(input: &amp;str) -&gt; Result&lt;String, Error&gt; {
   unimplemented!(&quot;Convert the input '{}' to a string&quot;, input);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-80" id="3-测试代码查看-80"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn input_with_lines_not_multiple_of_four_is_error() {
   let input = &quot; _ \n&quot;.to_string() +
               &quot;| |\n&quot; +
               &quot;   &quot;;

   assert_eq!(Err(Error::InvalidRowCount(3)), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn input_with_columns_not_multiple_of_three_is_error() {
   let input = &quot;    \n&quot;.to_string() +
               &quot;   |\n&quot; +
               &quot;   |\n&quot; +
               &quot;    &quot;;

   assert_eq!(Err(Error::InvalidColumnCount(4)), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn unrecognized_characters_return_question_mark() {
   let input = &quot;   \n&quot;.to_string() +
               &quot;  _\n&quot; +
               &quot;  |\n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;?&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_0() {
   let input = &quot; _ \n&quot;.to_string() +
               &quot;| |\n&quot; +
               &quot;|_|\n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;0&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_1() {
   let input = &quot;   \n&quot;.to_string() +
               &quot;  |\n&quot; +
               &quot;  |\n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;1&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_2() {
   let input = &quot; _ \n&quot;.to_string() +
               &quot; _|\n&quot; +
               &quot;|_ \n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;2&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_3() {
   let input = &quot; _ \n&quot;.to_string() +
               &quot; _|\n&quot; +
               &quot; _|\n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;3&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_4() {
   let input = &quot;   \n&quot;.to_string() +
               &quot;|_|\n&quot; +
               &quot;  |\n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;4&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_5() {
   let input = &quot; _ \n&quot;.to_string() +
               &quot;|_ \n&quot; +
               &quot; _|\n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;5&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_6() {
   let input = &quot; _ \n&quot;.to_string() +
               &quot;|_ \n&quot; +
               &quot;|_|\n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;6&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_7() {
   let input = &quot; _ \n&quot;.to_string() +
               &quot;  |\n&quot; +
               &quot;  |\n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;7&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_8() {
   let input = &quot; _ \n&quot;.to_string() +
               &quot;|_|\n&quot; +
               &quot;|_|\n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;8&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_9() {
   let input = &quot; _ \n&quot;.to_string() +
               &quot;|_|\n&quot; +
               &quot; _|\n&quot; +
               &quot;   &quot;;

   assert_eq!(Ok(&quot;9&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_110101100() {
   let input = &quot;       _     _        _  _ \n&quot;.to_string() +
               &quot;  |  || |  || |  |  || || |\n&quot; +
               &quot;  |  ||_|  ||_|  |  ||_||_|\n&quot; +
               &quot;                           &quot;;

   assert_eq!(Ok(&quot;110101100&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn replaces_only_garbled_numbers_with_question_mark() {
   let input = &quot;       _     _           _ \n&quot;.to_string() +
               &quot;  |  || |  || |     || || |\n&quot; +
               &quot;  |  | _|  ||_|  |  ||_||_|\n&quot; +
               &quot;                           &quot;;

   assert_eq!(Ok(&quot;11?10?1?0&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn recognizes_string_of_decimal_numbers() {
   let input = &quot;    _  _     _  _  _  _  _  _ \n&quot;.to_string() +
               &quot;  | _| _||_||_ |_   ||_||_|| |\n&quot; +
               &quot;  ||_  _|  | _||_|  ||_| _||_|\n&quot; +
               &quot;                              &quot;;

   assert_eq!(Ok(&quot;1234567890&quot;.to_string()), convert(&amp;input));
}

#[test]
//#[ignore]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn numbers_across_multiple_lines_are_joined_by_commas() {
   let input = &quot;    _  _ \n&quot;.to_string() +
               &quot;  | _| _|\n&quot; +
               &quot;  ||_  _|\n&quot; +
               &quot;         \n&quot; +
               &quot;    _  _ \n&quot; +
               &quot;|_||_ |_ \n&quot; +
               &quot;  | _||_|\n&quot; +
               &quot;         \n&quot; +
               &quot; _  _  _ \n&quot; +
               &quot;  ||_||_|\n&quot; +
               &quot;  ||_| _|\n&quot; +
               &quot;         &quot;;
   assert_eq!(Ok(&quot;123,456,789&quot;.to_string()), convert(&amp;input));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-80" id="4-答案-80"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::BTreeMap;

#[derive(Debug, PartialEq)]
pub enum Error {
   InvalidRowCount(usize),
   InvalidColumnCount(usize),
}

pub fn convert(input: &amp;str) -&gt; Result&lt;String, Error&gt; {
   let line_count = input.lines().count();
   if line_count % 4 != 0 {
       return Err(Error::InvalidRowCount(line_count));
   }
   for line in input.lines() {
       let char_count = line.chars().count();
       if char_count % 3 != 0 {
           return Err(Error::InvalidColumnCount(char_count));
       }
   }

   let y = input.lines().collect::&lt;Vec&lt;_&gt;&gt;();

   let mut converted_lines = vec![];

   for char_lines in y.chunks(4) {
       let mut unparsed_characters = BTreeMap::new();

       for line in char_lines {
           let line_chars = line.chars().collect::&lt;Vec&lt;_&gt;&gt;();

           for (char_number, char_chunk) in line_chars.chunks(3).enumerate() {
               let char_chars = unparsed_characters.entry(char_number).or_insert(vec![]);
               for c in char_chunk {
                   char_chars.push(*c);
               }
           }
       }

       let mut parsed_characters = String::new();

       for (_, v) in unparsed_characters {
           parsed_characters.push(convert_character(&amp;v));
       }

       converted_lines.push(parsed_characters.to_string());
   }

   Ok(converted_lines.join(&quot;,&quot;))
}

fn convert_character(input: &amp;Vec&lt;char&gt;) -&gt; char {
   if &amp;input[..] == [' ', '_', ' ', '|', ' ', '|', '|', '_', '|', ' ', ' ', ' '] {
       '0'
   } else if &amp;input[..] == [' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', '|', ' ', ' ', ' '] {
       '1'
   } else if &amp;input[..] == [' ', '_', ' ', ' ', '_', '|', '|', '_', ' ', ' ', ' ', ' '] {
       '2'
   } else if &amp;input[..] == [' ', '_', ' ', ' ', '_', '|', ' ', '_', '|', ' ', ' ', ' '] {
       '3'
   } else if &amp;input[..] == [' ', ' ', ' ', '|', '_', '|', ' ', ' ', '|', ' ', ' ', ' '] {
       '4'
   } else if &amp;input[..] == [' ', '_', ' ', '|', '_', ' ', ' ', '_', '|', ' ', ' ', ' '] {
       '5'
   } else if &amp;input[..] == [' ', '_', ' ', '|', '_', ' ', '|', '_', '|', ' ', ' ', ' '] {
       '6'
   } else if &amp;input[..] == [' ', '_', ' ', ' ', ' ', '|', ' ', ' ', '|', ' ', ' ', ' '] {
       '7'
   } else if &amp;input[..] == [' ', '_', ' ', '|', '_', '|', '|', '_', '|', ' ', ' ', ' '] {
       '8'
   } else if &amp;input[..] == [' ', '_', ' ', '|', '_', '|', ' ', '_', '|', ' ', ' ', ' '] {
       '9'
   } else {
       '?'
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-80" id="填充相关-80"><h2>填充/相关</h2></a>
<a class="header" href="#minesweeper" id="minesweeper"><h1>Minesweeper</h1></a>
<a class="header" href="#1-readme-81" id="1-readme-81"><h2>1. Readme</h2></a>
<a class="header" href="#扫雷" id="扫雷"><h1>扫雷</h1></a>
<p>将数字添加到扫雷板上.</p>
<p>扫雷器是一个流行的游戏，其中用户要用数字提示，来找到地雷，这些数字提示指示有多少地雷直接相邻(水平，垂直，对角，总 9 个格)，围成一个正方形.</p>
<p>在这个练习中，您必须创建一些代码，这些代码计算与正方形相邻的地雷数量，并且像这样转换地雷板(其中<code>*</code>表示地雷):</p>
<pre><code>    +-----+
    | * * |
    |  *  |
    |  *  |
    |     |
    +-----+
</code></pre>
<p>变成:</p>
<pre><code>    +-----+
    |1*3*1|
    |13*31|
    | 2*2 |
    | 111 |
    +-----+
</code></pre>
<a class="header" href="#2-开始你的表演-81" id="2-开始你的表演-81"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn annotate(minefield: &amp;[&amp;str]) -&gt; Vec&lt;String&gt; {
   unimplemented!(&quot;\nAnnotate each square of the given minefield with the number of mines that surround said square (blank if there are no surrounding mines):\n{:#?}\n&quot;, minefield);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-81" id="3-测试代码查看-81"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn remove_annotations(board: &amp;[&amp;str]) -&gt; Vec&lt;String&gt; {
   board.iter().map(|r| remove_annotations_in_row(r)).collect()
}

fn remove_annotations_in_row(row: &amp;str) -&gt; String {
   row.chars()
       .map(|ch| match ch {
           '*' =&gt; '*',
           _ =&gt; ' ',
       })
       .collect()
}

fn run_test(test_case: &amp;[&amp;str]) {
   let cleaned = remove_annotations(test_case);
   let cleaned_strs = cleaned.iter().map(|r| &amp;r[..]).collect::&lt;Vec&lt;_&gt;&gt;();
   let expected = test_case.iter().map(|&amp;r| r.to_string()).collect::&lt;Vec&lt;_&gt;&gt;();
   assert_eq!(expected, annotate(&amp;cleaned_strs));
}

#[test]
fn no_rows() {
   run_test(&amp;[]);
}

#[test]
//#[ignore]
fn no_columns() {
   run_test(&amp;[&quot;&quot;]);
}

#[test]
//#[ignore]
fn no_mines() {
   run_test(&amp;[&quot;   &quot;, &quot;   &quot;, &quot;   &quot;]);
}

#[test]
//#[ignore]
fn board_with_only_mines() {
   run_test(&amp;[&quot;***&quot;, &quot;***&quot;, &quot;***&quot;]);
}

#[test]
//#[ignore]
fn mine_surrounded_by_spaces() {
   run_test(&amp;[&quot;111&quot;, &quot;1*1&quot;, &quot;111&quot;]);
}

#[test]
//#[ignore]
fn space_surrounded_by_mines() {
   run_test(&amp;[&quot;***&quot;, &quot;*8*&quot;, &quot;***&quot;]);
}

#[test]
//#[ignore]
fn horizontal_line() {
   run_test(&amp;[&quot;1*2*1&quot;]);
}

#[test]
//#[ignore]
fn horizontal_line_mines_at_edges() {
   run_test(&amp;[&quot;*1 1*&quot;]);
}

#[test]
//#[ignore]
fn vertical_line() {
   run_test(&amp;[&quot;1&quot;, &quot;*&quot;, &quot;2&quot;, &quot;*&quot;, &quot;1&quot;]);
}

#[test]
//#[ignore]
fn vertical_line_mines_at_edges() {
   run_test(&amp;[&quot;*&quot;, &quot;1&quot;, &quot; &quot;, &quot;1&quot;, &quot;*&quot;]);
}

#[test]
//#[ignore]
fn cross() {
   run_test(&amp;[&quot; 2*2 &quot;, &quot;25*52&quot;, &quot;*****&quot;, &quot;25*52&quot;, &quot; 2*2 &quot;]);
}

#[test]
//#[ignore]
fn large_board() {
   run_test(&amp;[&quot;1*22*1&quot;, &quot;12*322&quot;, &quot; 123*2&quot;, &quot;112*4*&quot;, &quot;1*22*2&quot;, &quot;111111&quot;]);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-81" id="4-答案-81"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
struct Board {
   pieces: Vec&lt;Vec&lt;char&gt;&gt;,
   num_rows: usize,
   num_cols: usize
}

impl Board {
   fn annotated(&amp;self) -&gt; Vec&lt;String&gt; {
       (0..self.num_rows).map(|y| self.annotated_row(y)).collect()
   }

   fn annotated_row(&amp;self, y: usize) -&gt; String {
       self.pieces[y]
                 .iter()
                 .enumerate()
                 .map(|(x,&amp;c)| if c == ' ' {self.count_neighbouring_mines_char(x, y)} else {c})
                 .collect::&lt;String&gt;()
   }

   fn count_neighbouring_mines_char(&amp;self, x: usize, y: usize) -&gt; char {
       let mut count = 0;
       for x1 in neighbouring_points(x, self.num_cols) {
           for y1 in neighbouring_points(y, self.num_rows) {
               let piece = self.pieces[y1][x1];
               if piece == '*' {
                   count += 1;
               }
           }
       }
       if count == 0 {
           ' '
       } else {
           (('0' as u8) + count) as char
       }
   }
}

pub fn annotate(pieces: &amp;[&amp;str]) -&gt; Vec&lt;String&gt; {
   if pieces.len() == 0 {
       return Vec::new();
   }
   let pieces_vec = pieces.iter().map(|&amp;r| r.chars().collect()).collect();
   Board {pieces: pieces_vec, num_rows: pieces.len(), num_cols: pieces[0].len()}.annotated()
}

fn neighbouring_points(x: usize, limit: usize) -&gt; Vec&lt;usize&gt; {
   let mut offsets = vec![x];
   if x &gt;= 1 {
       offsets.push(x-1);
   }
   if x+2 &lt;= limit {
       offsets.push(x+1);
   }
   offsets
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-81" id="填充相关-81"><h2>填充/相关</h2></a>
<a class="header" href="#dominoes" id="dominoes"><h1>Dominoes</h1></a>
<a class="header" href="#1-readme-82" id="1-readme-82"><h2>1. Readme</h2></a>
<a class="header" href="#多米诺骨牌" id="多米诺骨牌"><h1>多米诺骨牌</h1></a>
<p>制作一个多米诺骨牌.</p>
<p>计算给出的多米诺骨牌的排序方法，使它们形成一个正确的多米诺骨牌链(石头的一半上的数值，与相邻石头的一半上的数值相匹配)，并且(第一块石头和最后一块石头)石头的一半上的数值没有邻居，且它们的数值匹配.</p>
<p>比如，给出石头<code>[2|1]</code>，<code>[2|3]</code>和<code>[1|3]</code>你应该计算一些类似<code>[1|2] [2|3] [3|1]</code>或<code>[3|2] [2|1] [1|3]</code>或<code>[1|3] [3|2] [2|1]</code>的东西等，其中第一个和最后一个数字是相同的。</p>
<p>对于以下石头<code>[1|2]</code>，<code>[4|1]</code>和<code>[2|3]</code>，它的结果骨牌链无效：<code>[4|1] [1|2] [2|3]</code>第一个和最后一个数字不一样。4!= 3</p>
<p>一些测试用例可以在一个骨牌链解决方案中，使用重复的石头，假设使用了多个骨牌集合。</p>
<a class="header" href="#2-开始你的表演-82" id="2-开始你的表演-82"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn chain(input: &amp;[(u8, u8)]) -&gt; Option&lt;Vec&lt;(u8, u8)&gt;&gt; {
   unimplemented!(&quot;From the given input '{:?}' construct a proper dominoes chain or return None if it is not possible.&quot;, input);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-82" id="3-测试代码查看-82"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// type Domino = (u8, u8);

#[derive(Debug)]
enum CheckResult {
   GotInvalid, // chain returned None
   Correct,
   ChainingFailure(Vec&lt;Domino&gt;), // failure to match the dots at the right side of one domino with
   // the one on the left side of the next
   LengthMismatch(Vec&lt;Domino&gt;),
   DominoMismatch(Vec&lt;Domino&gt;), // different dominoes are used in input and output
}

use CheckResult::*;

fn normalize(d: &amp;Domino) -&gt; Domino {
   match d {
       &amp;(m, n) if m &gt; n =&gt; (n, m),
       &amp;(m, n) =&gt; (m, n),
   }
}

fn check(input: &amp;[Domino]) -&gt; CheckResult {
   let output = match chain(input) {
       None =&gt; return GotInvalid,
       Some(o) =&gt; o,
   };
   if input.len() != output.len() {
       return LengthMismatch(output);
   } else if input.len() == 0 {
       // and thus output.len() == 0
       return Correct;
   }

   let mut output_sorted = output.iter().map(|d| normalize(d)).collect::&lt;Vec&lt;Domino&gt;&gt;();
   output_sorted.sort();
   let mut input_sorted = input.iter().map(|d| normalize(d)).collect::&lt;Vec&lt;Domino&gt;&gt;();
   input_sorted.sort();
   if input_sorted != output_sorted {
       return DominoMismatch(output);
   }

   // both input and output have at least 1 element
   // This essentially puts the first element after the last one, thereby making it
   // easy to check whether the domino chains &quot;wraps around&quot;.
   let mut fail = false;
   {
       let mut n = output[0].1;
       let iter = output.iter().skip(1).chain(output.iter().take(1));
       for &amp;(first, second) in iter {
           if n != first {
               fail = true;
               break;
           }
           n = second
       }
   }
   if fail {
       ChainingFailure(output)
   } else {
       Correct
   }
}

fn assert_correct(input: &amp;[Domino]) {
   match check(&amp;input) {
       Correct =&gt; (),
       GotInvalid =&gt; panic!(&quot;Unexpectedly got invalid on input {:?}&quot;, input),
       ChainingFailure(output) =&gt; panic!(
           &quot;Chaining failure for input {:?}, output {:?}&quot;,
           input, output
       ),
       LengthMismatch(output) =&gt; {
           panic!(&quot;Length mismatch for input {:?}, output {:?}&quot;, input, output)
       }
       DominoMismatch(output) =&gt; {
           panic!(&quot;Domino mismatch for input {:?}, output {:?}&quot;, input, output)
       }
   }
}

#[test]
fn empty_input_empty_output() {
   let input = &amp;[];
   assert_eq!(chain(input), Some(vec![]));
}

#[test]
//#[ignore]
fn singleton_input_singleton_output() {
   let input = &amp;[(1, 1)];
   assert_correct(input);
}

#[test]
//#[ignore]
fn singleton_that_cant_be_chained() {
   let input = &amp;[(1, 2)];
   assert_eq!(chain(input), None);
}

#[test]
//#[ignore]
fn no_repeat_numbers() {
   let input = &amp;[(1, 2), (3, 1), (2, 3)];
   assert_correct(input);
}

#[test]
//#[ignore]
fn can_reverse_dominoes() {
   let input = &amp;[(1, 2), (1, 3), (2, 3)];
   assert_correct(input);
}

#[test]
//#[ignore]
fn no_chains() {
   let input = &amp;[(1, 2), (4, 1), (2, 3)];
   assert_eq!(chain(input), None);
}

#[test]
//#[ignore]
fn disconnected_simple() {
   let input = &amp;[(1, 1), (2, 2)];
   assert_eq!(chain(input), None);
}

#[test]
//#[ignore]
fn disconnected_double_loop() {
   let input = &amp;[(1, 2), (2, 1), (3, 4), (4, 3)];
   assert_eq!(chain(input), None);
}

#[test]
//#[ignore]
fn disconnected_single_isolated() {
   let input = &amp;[(1, 2), (2, 3), (3, 1), (4, 4)];
   assert_eq!(chain(input), None);
}

#[test]
//#[ignore]
fn need_backtrack() {
   let input = &amp;[(1, 2), (2, 3), (3, 1), (2, 4), (2, 4)];
   assert_correct(input);
}

#[test]
//#[ignore]
fn separate_loops() {
   let input = &amp;[(1, 2), (2, 3), (3, 1), (1, 1), (2, 2), (3, 3)];
   assert_correct(input);
}

#[test]
//#[ignore]
fn nine_elements() {
   let input = &amp;[
       (1, 2),
       (5, 3),
       (3, 1),
       (1, 2),
       (2, 4),
       (1, 6),
       (2, 3),
       (3, 4),
       (5, 6),
   ];
   assert_correct(input);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-82" id="4-答案-82"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::iter;

pub type Domino = (u8, u8);

/// A table keeping track of available dominoes.
///
/// Effectively a 6x6 matrix. Each position denotes whether a domino is available with that column
/// dots and row dots. Positions are mirrored ((3,4) == (4,3)), except for positions with equal row
/// and column numbers.
struct AvailabilityTable {
   m: Vec&lt;u8&gt;,
}

impl AvailabilityTable {
   fn new() -&gt; AvailabilityTable {
       AvailabilityTable {
           m: iter::repeat(0).take(6 * 6).collect(),
       }
   }

   fn get(&amp;self, x: u8, y: u8) -&gt; u8 {
       self.m[((x - 1) * 6 + (y - 1)) as usize]
   }

   fn set(&amp;mut self, x: u8, y: u8, v: u8) {
       let m = &amp;mut self.m[..];
       m[((x - 1) * 6 + (y - 1)) as usize] = v;
   }

   fn add(&amp;mut self, x: u8, y: u8) {
       if x == y {
           let n = self.get(x, y);
           self.set(x, y, n + 1) // Along the diagonal
       } else {
           let m = self.get(x, y);
           self.set(x, y, m + 1);
           let n = self.get(y, x);
           self.set(y, x, n + 1);
       }
   }

   fn remove(&amp;mut self, x: u8, y: u8) {
       if self.get(x, y) &gt; 0 {
           if x == y {
               let n = self.get(x, y);
               self.set(x, y, n - 1) // Along the diagonal
           } else {
               let m = self.get(x, y);
               self.set(x, y, m - 1);
               let n = self.get(y, x);
               self.set(y, x, n - 1);
           }
       } else {
           // For this toy code hard explicit fail is best
           panic!(&quot;remove for 0 stones: ({:?}, {:?})&quot;, x, y)
       }
   }

   fn pop_first(&amp;mut self, x: u8) -&gt; Option&lt;u8&gt; {
       for y in 1..7 {
           if self.get(x, y) &gt; 0 {
               self.remove(x, y);
               return Some(y);
           }
       }
       None
   }
}

pub fn chain(dominoes: &amp;[Domino]) -&gt; Option&lt;Vec&lt;Domino&gt;&gt; {
   match dominoes.len() {
       0 =&gt; Some(vec![]),
       1 =&gt; if dominoes[0].0 == dominoes[0].1 {
           Some(vec![dominoes[0]])
       } else {
           None
       },
       _ =&gt; {
           // First check if the total number of each amount of dots is even, if not it's not
           // possible to complete a cycle. This follows from that it's an Eulerian path.
           let mut v: Vec&lt;u8&gt; = vec![0, 0, 0, 0, 0, 0];
           // Keep the mutable borrow in a small scope here to allow v.iter().
           {
               let vs = &amp;mut v[..];
               for dom in dominoes.iter() {
                   vs[dom.0 as usize - 1] += 1;
                   vs[dom.1 as usize - 1] += 1;
               }
           }
           for n in v.iter() {
               if n % 2 != 0 {
                   return None;
               }
           }
           let chain = chain_worker(dominoes);
           if chain.len() == dominoes.len() {
               Some(chain)
           } else {
               None
           }
       }
   }
}

fn chain_worker(dominoes: &amp;[Domino]) -&gt; Vec&lt;Domino&gt; {
   let mut doms = dominoes.to_vec();
   let first = doms.pop().unwrap();
   let mut t = AvailabilityTable::new();
   for dom in doms.iter() {
       t.add(dom.0, dom.1)
   }
   let mut v: Vec&lt;Domino&gt; = Vec::new();
   v.push(first);
   let mut n = first.1; // Number to connect to
   while let Some(m) = t.pop_first(n) {
       v.push((n, m));
       n = m;
   }
   v
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-82" id="填充相关-82"><h2>填充/相关</h2></a>
<a class="header" href="#parallel-letter-frequency" id="parallel-letter-frequency"><h1>Parallel Letter Frequency</h1></a>
<a class="header" href="#1-readme-83" id="1-readme-83"><h2>1. Readme</h2></a>
<a class="header" href="#并发字母频率" id="并发字母频率"><h1>并发字母频率</h1></a>
<p>使用并行计算，文本中的字母频率。</p>
<p>并行性是并行的，也可以按顺序进行。一个常见的例子是计算字母的频率。创建一个函数，返回文本列表中每个字母的总频率，并使用并行性。</p>
<a class="header" href="#rust-中的并发性字母频率" id="rust-中的并发性字母频率"><h1>Rust 中的并发性字母频率</h1></a>
<p>在这里了解更多关于 Rust 的并发性:</p>
<ul>
<li><a href="https://doc.rust-lang.org/book/ch16-00-concurrency.html">Concurrency</a></li>
</ul>
<a class="header" href="#加分-5" id="加分-5"><h2>加分</h2></a>
<p>这个练习还包括一个基准，以一个顺序实现为基线。您可以将您的解决方案与基准进行比较。观察不同大小的输入，对每个性能的影响。可以使用并行编程技术。来超越基准吗?</p>
<p>在本文中，<code>test::Bencher</code> 是不稳定的，只能在<em>nightly</em>Rust 可用。用 Cargo 运行基准:</p>
<pre><code class="language-bash">cargo bench
</code></pre>
<p>如果你使用 rustup.rs:</p>
<pre><code>rustup run nightly cargo bench
</code></pre>
<ul>
<li><a href="https://doc.rust-lang.org/stable/unstable-book/library-features/test.html">基准测试</a></li>
</ul>
<p>了解 nightly Rust 的更多信息:</p>
<ul>
<li><a href="https://doc.rust-lang.org/stable/book/2018-edition/appendix-06-nightly-rust.html">Nightly Rust</a></li>
<li><a href="https://github.com/rust-lang-nursery/rustup.rs#working-with-nightly-rust">Rustup: Working with nightly</a></li>
</ul>
<a class="header" href="#2-开始你的表演-83" id="2-开始你的表演-83"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::collections::HashMap;

pub fn frequency(input: &amp;[&amp;str], worker_count: usize) -&gt; HashMap&lt;char, usize&gt; {
   unimplemented!(
       &quot;Count the frequency of letters in the given input '{:?}'. Ensure that you are using {} to process the input.&quot;,
       input,
       match worker_count {
           1 =&gt; format!(&quot;1 worker&quot;),
           _ =&gt; format!(&quot;{} workers&quot;, worker_count),
       }
   );
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-83" id="3-测试代码查看-83"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// use std::collections::HashMap;

// Poem by Friedrich Schiller. The corresponding music is the European Anthem.
const ODE_AN_DIE_FREUDE: [&amp;'static str; 8] = [
   &quot;Freude schöner Götterfunken&quot;,
   &quot;Tochter aus Elysium,&quot;,
   &quot;Wir betreten feuertrunken,&quot;,
   &quot;Himmlische, dein Heiligtum!&quot;,
   &quot;Deine Zauber binden wieder&quot;,
   &quot;Was die Mode streng geteilt;&quot;,
   &quot;Alle Menschen werden Brüder,&quot;,
   &quot;Wo dein sanfter Flügel weilt.&quot;,
];

// Dutch national anthem
const WILHELMUS: [&amp;'static str; 8] = [
   &quot;Wilhelmus van Nassouwe&quot;,
   &quot;ben ik, van Duitsen bloed,&quot;,
   &quot;den vaderland getrouwe&quot;,
   &quot;blijf ik tot in den dood.&quot;,
   &quot;Een Prinse van Oranje&quot;,
   &quot;ben ik, vrij, onverveerd,&quot;,
   &quot;den Koning van Hispanje&quot;,
   &quot;heb ik altijd geëerd.&quot;,
];

// American national anthem
const STAR_SPANGLED_BANNER: [&amp;'static str; 8] = [
   &quot;O say can you see by the dawn's early light,&quot;,
   &quot;What so proudly we hailed at the twilight's last gleaming,&quot;,
   &quot;Whose broad stripes and bright stars through the perilous fight,&quot;,
   &quot;O'er the ramparts we watched, were so gallantly streaming?&quot;,
   &quot;And the rockets' red glare, the bombs bursting in air,&quot;,
   &quot;Gave proof through the night that our flag was still there;&quot;,
   &quot;O say does that star-spangled banner yet wave,&quot;,
   &quot;O'er the land of the free and the home of the brave?&quot;,
];

#[test]
fn test_no_texts() {
   assert_eq!(frequency(&amp;[], 4), HashMap::new());
}

#[test]
//#[ignore]
fn test_one_letter() {
   let mut hm = HashMap::new();
   hm.insert('a', 1);
   assert_eq!(frequency(&amp;[&quot;a&quot;], 4), hm);
}

#[test]
//#[ignore]
fn test_case_insensitivity() {
   let mut hm = HashMap::new();
   hm.insert('a', 2);
   assert_eq!(frequency(&amp;[&quot;aA&quot;], 4), hm);
}

#[test]
//#[ignore]
fn test_many_empty_lines() {
   let mut v = Vec::with_capacity(1000);
   for _ in 0..1000 {
       v.push(&quot;&quot;);
   }
   assert_eq!(frequency(&amp;v[..], 4), HashMap::new());
}

#[test]
//#[ignore]
fn test_many_times_same_text() {
   let mut v = Vec::with_capacity(1000);
   for _ in 0..1000 {
       v.push(&quot;abc&quot;);
   }
   let mut hm = HashMap::new();
   hm.insert('a', 1000);
   hm.insert('b', 1000);
   hm.insert('c', 1000);
   assert_eq!(frequency(&amp;v[..], 4), hm);
}

#[test]
//#[ignore]
fn test_punctuation_doesnt_count() {
   assert!(!frequency(&amp;WILHELMUS, 4).contains_key(&amp;','));
}

#[test]
//#[ignore]
fn test_numbers_dont_count() {
   assert!(!frequency(&amp;[&quot;Testing, 1, 2, 3&quot;], 4).contains_key(&amp;'1'));
}

#[test]
//#[ignore]
fn test_all_three_anthems_1_worker() {
   let mut v = Vec::new();
   for anthem in [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER].iter() {
       for line in anthem.iter() {
           v.push(*line);
       }
   }
   let freqs = frequency(&amp;v[..], 1);
   assert_eq!(freqs.get(&amp;'a'), Some(&amp;49));
   assert_eq!(freqs.get(&amp;'t'), Some(&amp;56));
   assert_eq!(freqs.get(&amp;'ü'), Some(&amp;2));
}

#[test]
//#[ignore]
fn test_all_three_anthems_3_workers() {
   let mut v = Vec::new();
   for anthem in [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER].iter() {
       for line in anthem.iter() {
           v.push(*line);
       }
   }
   let freqs = frequency(&amp;v[..], 3);
   assert_eq!(freqs.get(&amp;'a'), Some(&amp;49));
   assert_eq!(freqs.get(&amp;'t'), Some(&amp;56));
   assert_eq!(freqs.get(&amp;'ü'), Some(&amp;2));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-83" id="4-答案-83"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;
use std::sync::mpsc::channel;
use std::thread;

/// Compute the frequency of each letter (technically of each unicode codepoint) using the given
/// number of worker threads.
pub fn frequency(texts: &amp;[&amp;str], num_workers: usize) -&gt; HashMap&lt;char, usize&gt; {
   assert!(num_workers &gt; 0);
   let part_size_floor = texts.len() / num_workers;
   let rem = texts.len() % num_workers;
   let part_size = if rem &gt; 0 {
       part_size_floor + 1
   } else {
       part_size_floor
   };
   let mut parts: Vec&lt;Vec&lt;String&gt;&gt; = Vec::with_capacity(part_size);
   for _ in 0..num_workers {
       parts.push(Vec::with_capacity(part_size));
   }
   let mut i = 0;
   for line in texts.iter() {
       // We'll need to clone those strings in order to satisfy some lifetime guarantees. Basically
       // it's hard for the system to be sure that the threads spawned don't outlive the strings.
       parts[i].push(line.to_string());
       i = (i + 1) % num_workers;
   }

   let (tx, rx) = channel();

   for part in parts {
       let tx = tx.clone();
       thread::spawn(move || {
           tx.send(count(part)).unwrap();
       });
   }

   let mut results: HashMap&lt;char, usize&gt; = HashMap::new();
   for _ in 0..num_workers {
       let part_results = rx.recv().unwrap();
       for (c, n) in part_results.into_iter() {
           *results.entry(c).or_insert(0) += n;
       }
   }
   results
}

fn count(lines: Vec&lt;String&gt;) -&gt; HashMap&lt;char, usize&gt; {
   let mut results: HashMap&lt;char, usize&gt; = HashMap::new();
   for line in lines.iter() {
       for c in line.chars() {
           if c.is_alphabetic() {
               *results.entry(c.to_lowercase().next().unwrap()).or_insert(0) += 1;
           }
       }
   }
   results
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-83" id="填充相关-83"><h2>填充/相关</h2></a>
<a class="header" href="#rectangles" id="rectangles"><h1>Rectangles</h1></a>
<a class="header" href="#1-readme-84" id="1-readme-84"><h2>1. Readme</h2></a>
<a class="header" href="#矩形" id="矩形"><h1>矩形</h1></a>
<p>计算 ASCII 图中的矩形的数目，如下所示.</p>
<pre><code class="language-text">   +--+
  ++  |
+-++--+
|  |  |
+--+--+
</code></pre>
<p>上面的图表包含 6 个矩形:</p>
<pre><code class="language-text">+-----+
|     |
+-----+
</code></pre>
<pre><code class="language-text">   +--+
   |  |
   |  |
   |  |
   +--+
</code></pre>
<pre><code class="language-text">   +--+
   |  |
   +--+
</code></pre>
<pre><code class="language-text">   +--+
   |  |
   +--+
</code></pre>
<pre><code class="language-text">+--+
|  |
+--+
</code></pre>
<pre><code class="language-text">  ++
  ++
</code></pre>
<p>你可以假设输入总是一个适当的矩形(即每行的长度，等于第一行的长度)。</p>
<a class="header" href="#2-开始你的表演-84" id="2-开始你的表演-84"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn count(lines: &amp;[&amp;str]) -&gt; u32 {
   unimplemented!(&quot;\nDetermine the count of rectangles in the ASCII diagram represented by the following lines:\n{:#?}\n.&quot;, lines);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-84" id="3-测试代码查看-84"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_zero_area_1() {
   let lines = &amp;[];
   assert_eq!(0, count(lines))
}

#[test]
//#[ignore]
fn test_zero_area_2() {
   let lines = &amp;[&quot;&quot;];
   assert_eq!(0, count(lines))
}

#[test]
//#[ignore]
fn test_empty_area() {
   let lines = &amp;[&quot; &quot;];
   assert_eq!(0, count(lines))
}

#[test]
//#[ignore]
fn test_one_rectangle() {
   let lines = &amp;[&quot;+-+&quot;, &quot;| |&quot;, &quot;+-+&quot;];
   assert_eq!(1, count(lines))
}

#[test]
//#[ignore]
fn test_two_rectangles_no_shared_parts() {
   let lines = &amp;[&quot;  +-+&quot;, &quot;  | |&quot;, &quot;+-+-+&quot;, &quot;| |  &quot;, &quot;+-+  &quot;];
   assert_eq!(2, count(lines))
}

#[test]
//#[ignore]
fn test_five_rectangles_three_regions() {
   let lines = &amp;[&quot;  +-+&quot;, &quot;  | |&quot;, &quot;+-+-+&quot;, &quot;| | |&quot;, &quot;+-+-+&quot;];
   assert_eq!(5, count(lines))
}

#[test]
//#[ignore]
fn rectangle_of_height_1() {
   let lines = &amp;[&quot;+--+&quot;, &quot;+--+&quot;];
   assert_eq!(1, count(lines))
}

#[test]
//#[ignore]
fn rectangle_of_width_1() {
   let lines = &amp;[&quot;++&quot;, &quot;||&quot;, &quot;++&quot;];
   assert_eq!(1, count(lines))
}

#[test]
//#[ignore]
fn unit_square() {
   let lines = &amp;[&quot;++&quot;, &quot;++&quot;];
   assert_eq!(1, count(lines))
}

#[test]
//#[ignore]
fn test_incomplete_rectangles() {
   let lines = &amp;[&quot;  +-+&quot;, &quot;    |&quot;, &quot;+-+-+&quot;, &quot;| | -&quot;, &quot;+-+-+&quot;];
   assert_eq!(1, count(lines))
}

#[test]
//#[ignore]
fn test_complicated() {
   let lines = &amp;[
       &quot;+------+----+&quot;,
       &quot;|      |    |&quot;,
       &quot;+---+--+    |&quot;,
       &quot;|   |       |&quot;,
       &quot;+---+-------+&quot;,
   ];
   assert_eq!(3, count(lines))
}

#[test]
//#[ignore]
fn test_not_so_complicated() {
   let lines = &amp;[
       &quot;+------+----+&quot;,
       &quot;|      |    |&quot;,
       &quot;+------+    |&quot;,
       &quot;|   |       |&quot;,
       &quot;+---+-------+&quot;,
   ];
   assert_eq!(2, count(lines))
}

#[test]
//#[ignore]
fn test_large_input_with_many_rectangles() {
   let lines = &amp;[
       &quot;+---+--+----+&quot;,
       &quot;|   +--+----+&quot;,
       &quot;+---+--+    |&quot;,
       &quot;|   +--+----+&quot;,
       &quot;+---+--+--+-+&quot;,
       &quot;+---+--+--+-+&quot;,
       &quot;+------+  | |&quot;,
       &quot;          +-+&quot;,
   ];
   assert_eq!(60, count(lines))
}

#}</code></pre></pre>
<a class="header" href="#4-答案-84" id="4-答案-84"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::{HashMap, HashSet};

// We first look for corners that are connected by a straight uninterrupted line.
// At the same time we make a note for each corner in which direction it's connected.
//
// Later we simply scan over the corners, pairing each top-left with each right-bottom corner
// (provided it's to the right and below the top-left corner) and look if all four lines
// of the rectangle exist.
//
// To simplify scanning for lines and points we run the horizontal lines algorithm on a
// seemingly transposed version of the input and later transpose the results again.

// Note: values of these constants are used in transposition, they're not random.
const CONN_LEFT: u8 = 0x1;
const CONN_RIGHT: u8 = 0x2;
const CONN_UP: u8 = 0x4;
const CONN_DOWN: u8 = 0x8;

#[derive(PartialEq, Eq, Hash)]
struct Point {
   x: usize,
   y: usize
}

#[derive(PartialEq, Eq, Hash)]
struct Line {
   x1: usize,
   y1: usize,
   x2: usize,
   y2: usize
}

#[derive(PartialEq, Eq, Clone, Copy)]
enum Symbol {
   Corner, // '+'
   Connect, // '|' or '-' depending on direction
   Other // ' ', or anything really
}

// The input area.
struct RealArea {
   width: usize,
   height: usize,
   chars: Vec&lt;Vec&lt;char&gt;&gt;
}

trait Area {
   fn width(&amp;self) -&gt; usize;
   fn height(&amp;self) -&gt; usize;
   fn symbol_at(&amp;self, x: usize, y: usize) -&gt; Symbol;
}

// For horizontal scanning
impl Area for RealArea {
   fn width(&amp;self) -&gt; usize { self.width }
   fn height(&amp;self) -&gt; usize { self.height }
   fn symbol_at(&amp;self, x: usize, y: usize) -&gt; Symbol {
       match self.chars[y][x] {
           '+' =&gt; Symbol::Corner,
           '-' =&gt; Symbol::Connect,
           _ =&gt; Symbol::Other
       }
   }
}

struct TransposedArea&lt;'a&gt;(&amp;'a RealArea);

// For vertical scanning
impl&lt;'a&gt; Area for TransposedArea&lt;'a&gt; {
   fn width(&amp;self) -&gt; usize { self.0.height }
   fn height(&amp;self) -&gt; usize { self.0.width }
   fn symbol_at(&amp;self, x: usize, y: usize) -&gt; Symbol {
       match self.0.chars[x][y] {
           '+' =&gt; Symbol::Corner,
           '|' =&gt; Symbol::Connect,
           _ =&gt; Symbol::Other
       }
   }
}

// Information about connections.
struct Connections {
   lines: HashSet&lt;Line&gt;,
   points: HashMap&lt;Point, u8&gt;
}

pub fn count(lines: &amp;[&amp;str]) -&gt; usize {
   if lines.len() == 0 {
       return 0
   } else if lines[0].len() == 0 {
       return 0
   }
   let area = RealArea {
       width: lines[0].len(),
       height: lines.len(),
       chars: lines.iter().map(|line| line.chars().collect()).collect()
   };
   let area_transposed = TransposedArea(&amp;area);
   let mut conns = scan_connected(&amp;area);
   let conns_transposed = scan_connected(&amp;area_transposed);

   // The transposed connections have their coordinate system wrong,
   // correct this.
   for l in conns_transposed.lines {
       conns.lines.insert(Line{x1: l.y1, y1: l.x1, x2: l.y2, y2: l.x2});
   }
   for (p, tcf) in conns_transposed.points {
       let cf = conns.points.entry(Point{x: p.y, y: p.x}).or_insert(0);
       *cf = *cf | (tcf &lt;&lt; 2)
   }

   let mut total = 0;
   for (tl_p, tl_cf) in conns.points.iter() { // top left point and connection flags
       if tl_cf &amp; (CONN_RIGHT|CONN_DOWN) == CONN_RIGHT|CONN_DOWN {
           for (br_p, br_cf) in conns.points.iter() {
               // left, right, top, bottom of potential rectangle
               let l = tl_p.x;
               let r = br_p.x;
               let t = tl_p.y;
               let b = br_p.y;
               let is_rect =
                   br_cf &amp; (CONN_LEFT|CONN_UP) == CONN_LEFT|CONN_UP &amp;&amp;
                   r &gt; l &amp;&amp; b &gt; t &amp;&amp;
                   conns.lines.contains(&amp;Line{x1: l, y1: t, x2: l, y2: b}) &amp;&amp;
                   conns.lines.contains(&amp;Line{x1: l, y1: t, x2: r, y2: t}) &amp;&amp;
                   conns.lines.contains(&amp;Line{x1: l, y1: b, x2: r, y2: b}) &amp;&amp;
                   conns.lines.contains(&amp;Line{x1: r, y1: t, x2: r, y2: b});
               if is_rect {
                   total += 1
               }
           }
       }
   }
   return total;
}

fn scan_connected(area: &amp;Area) -&gt; Connections {
   let mut conns = Connections{
       lines: HashSet::new(),
       points: HashMap::new()
   };
   let mut connected: Vec&lt;usize&gt; = vec![];
   for y in 0..area.height() {
       connected.clear();
       for x in 0..area.width() {
           let sym = area.symbol_at(x, y);
           if sym == Symbol::Corner {
               for prev in connected.iter() {
                   conns.lines.insert(Line{x1: prev.clone(), y1: y, x2: x, y2: y});
               }
               if let Some(last) = connected.last() {
                   let cf = conns.points.get_mut(&amp;Point{x: last.clone(), y: y}).unwrap();
                   *cf = *cf | CONN_RIGHT;
               }
               let cf = conns.points.entry(Point{x: x, y: y}).or_insert(0);
               if connected.len() &gt; 0 {
                   *cf = *cf | CONN_LEFT;
               }
               connected.push(x);
           } else if sym != Symbol::Connect {
               connected.clear(); // End of connected bit.
           }
       }
   }
   conns
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-84" id="填充相关-84"><h2>填充/相关</h2></a>
<a class="header" href="#forth" id="forth"><h1>Forth</h1></a>
<a class="header" href="#1-readme-85" id="1-readme-85"><h2>1. Readme</h2></a>
<a class="header" href="#forth-1" id="forth-1"><h1>Forth</h1></a>
<p>为 Forth 的一个非常简单的子集，实现一个执行程序.</p>
<p><a href="https://en.wikipedia.org/wiki/Forth_%28programming_language%29">Forth</a>是一种基于栈的编程语言。为 Forth 的一小部分子集，实现一个非常基本的执行器。</p>
<p>您的执行器必须支持以下关键字:</p>
<ul>
<li><code>+</code>，<code>-</code>，<code>*</code>，<code>/</code>(整数运算)</li>
<li><code>DUP</code>，<code>DROP</code>，<code>SWAP</code>，<code>OVER</code>(栈操作)</li>
</ul>
<p>您的执行器还必须支持使用惯用语法，定义新单词:<code>: word-name definition ;</code>.</p>
<p>为简单起见，您需要支持的唯一数据类型是，至少 16 位大小的有符号整数。</p>
<p>您应该对语法使用以下规则：一个 number 是一个或多个(ASCII)数字的序列，单词是一个或多个字母，数字，符号或标点符号的序列，而不是数字。(Forth 可能使用稍微不同的规则，但这已足够接近。)</p>
<p>单词不区分大小写。</p>
<a class="header" href="#2-开始你的表演-85" id="2-开始你的表演-85"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub type Value = i32;
pub type ForthResult = Result&lt;(), Error&gt;;

pub struct Forth;

#[derive(Debug, PartialEq)]
pub enum Error {
   DivisionByZero,
   StackUnderflow,
   UnknownWord,
   InvalidWord,
}

impl Forth {
   pub fn new() -&gt; Forth {
       unimplemented!()
   }

   pub fn stack(&amp;self) -&gt; Vec&lt;Value&gt; {
       unimplemented!()
   }

   pub fn eval(&amp;mut self, input: &amp;str) -&gt; ForthResult {
       unimplemented!(&quot;result of evaluating '{}'&quot;, input)
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-85" id="3-测试代码查看-85"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn no_input_no_stack() {
   assert_eq!(Vec::&lt;Value&gt;::new(), Forth::new().stack());
}

#[test]
//#[ignore]
fn numbers_just_get_pushed_onto_the_stack() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;1 2 3 4 5 -1&quot;).is_ok());
   assert_eq!(vec![1, 2, 3, 4, 5, -1], f.stack());
}

#[test]
//#[ignore]
fn non_word_characters_are_separators() {
   let mut f = Forth::new();
   // Note the Ogham Space Mark ( ), this is a spacing character.
   assert!(f.eval(&quot;1\u{0000}2\u{0001}3\n4\r5 6\t7&quot;).is_ok());
   assert_eq!(vec![1, 2, 3, 4, 5, 6, 7], f.stack());
}

#[test]
//#[ignore]
fn basic_arithmetic_1() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;1 2 + 4 -&quot;).is_ok());
   assert_eq!(vec![-1], f.stack());
}

#[test]
//#[ignore]
fn basic_arithmetic_2() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;2 4 * 3 /&quot;).is_ok());
   assert_eq!(vec![2], f.stack());
}

#[test]
//#[ignore]
fn addition_error() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::StackUnderflow), f.eval(&quot;+&quot;));
}

#[test]
//#[ignore]
fn subtraction_error() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::StackUnderflow), f.eval(&quot;-&quot;));
}

#[test]
//#[ignore]
fn multiplication_error() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::StackUnderflow), f.eval(&quot;*&quot;));
}

#[test]
//#[ignore]
fn division_error() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::StackUnderflow), f.eval(&quot;/&quot;));
}

#[test]
//#[ignore]
fn division_by_zero() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::DivisionByZero), f.eval(&quot;4 2 2 - /&quot;));
}

#[test]
//#[ignore]
fn dup() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;1 DUP&quot;).is_ok());
   assert_eq!(vec![1, 1], f.stack());
}

#[test]
//#[ignore]
fn dup_case_insensitive() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;1 Dup&quot;).is_ok());
   assert_eq!(vec![1, 1], f.stack());
}

#[test]
//#[ignore]
fn dup_error() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::StackUnderflow), f.eval(&quot;dup&quot;));
}

#[test]
//#[ignore]
fn drop() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;1 drop&quot;).is_ok());
   assert_eq!(Vec::&lt;Value&gt;::new(), f.stack());
}

#[test]
//#[ignore]
fn drop_with_two() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;1 2 drop&quot;).is_ok());
   assert_eq!(vec![1], f.stack());
}

#[test]
//#[ignore]
fn drop_error() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::StackUnderflow), f.eval(&quot;drop&quot;));
}

#[test]
//#[ignore]
fn swap() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;1 2 swap&quot;).is_ok());
   assert_eq!(vec![2, 1], f.stack());
}

#[test]
//#[ignore]
fn swap_with_three() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;1 2 3 swap&quot;).is_ok());
   assert_eq!(vec![1, 3, 2], f.stack());
}

#[test]
//#[ignore]
fn swap_error() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::StackUnderflow), f.eval(&quot;1 swap&quot;));
   assert_eq!(Err(Error::StackUnderflow), f.eval(&quot;swap&quot;));
}

#[test]
//#[ignore]
fn over() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;1 2 over&quot;).is_ok());
   assert_eq!(vec![1, 2, 1], f.stack());
}

#[test]
//#[ignore]
fn over_with_three() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;1 2 3 over&quot;).is_ok());
   assert_eq!(vec![1, 2, 3, 2], f.stack());
}

#[test]
//#[ignore]
fn over_error() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::StackUnderflow), f.eval(&quot;1 over&quot;));
   assert_eq!(Err(Error::StackUnderflow), f.eval(&quot;over&quot;));
}

#[test]
//#[ignore]
fn defining_a_new_word() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;: CoUnT 1 2 3 ;&quot;).is_ok());
   assert!(f.eval(&quot;count COUNT&quot;).is_ok());
   assert_eq!(vec![1, 2, 3, 1, 2, 3], f.stack());
}

#[test]
//#[ignore]
fn redefining_an_existing_word() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;: foo dup ;&quot;).is_ok());
   assert!(f.eval(&quot;: foo dup dup ;&quot;).is_ok());
   assert!(f.eval(&quot;1 foo&quot;).is_ok());
   assert_eq!(vec![1, 1, 1], f.stack());
}

#[test]
//#[ignore]
fn redefining_an_existing_built_in_word() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;: swap dup ;&quot;).is_ok());
   assert!(f.eval(&quot;1 swap&quot;).is_ok());
   assert_eq!(vec![1, 1], f.stack());
}

#[test]
//#[ignore]
fn defining_words_with_odd_characters() {
   let mut f = Forth::new();
   assert!(f.eval(&quot;: € 220371 ; €&quot;).is_ok());
   assert_eq!(vec![220371], f.stack());
}

#[test]
//#[ignore]
fn defining_a_number() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::InvalidWord), f.eval(&quot;: 1 2 ;&quot;));
}

#[test]
//#[ignore]
fn malformed_word_definition() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::InvalidWord), f.eval(&quot;:&quot;));
   assert_eq!(Err(Error::InvalidWord), f.eval(&quot;: foo&quot;));
   assert_eq!(Err(Error::InvalidWord), f.eval(&quot;: foo 1&quot;));
}

#[test]
//#[ignore]
fn calling_non_existing_word() {
   let mut f = Forth::new();
   assert_eq!(Err(Error::UnknownWord), f.eval(&quot;1 foo&quot;));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-85" id="4-答案-85"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;
use std::collections::LinkedList;
use std::str::FromStr;

use Term::*;

pub type Value = i32;
pub type ForthResult = Result&lt;(), Error&gt;;
type StackResult&lt;T&gt; = Result&lt;T, Error&gt;;

type Stack = LinkedList&lt;Value&gt;;
type Code = LinkedList&lt;Term&gt;;
type Definitions = HashMap&lt;String, Code&gt;;

pub struct Forth {
   code: Code,
   defs: Definitions,
   stack: Stack,
}

#[derive(Debug, PartialEq)]
pub enum Error {
   DivisionByZero,
   StackUnderflow,
   UnknownWord,
   InvalidWord,
}

#[derive(Debug, Clone)]
enum Term {
   Number(Value),
   Word(String),
   StartDefinition,
   EndDefinition,
}

impl FromStr for Term {
   type Err = ();

   fn from_str(s: &amp;str) -&gt; Result&lt;Term, ()&gt; {
       match s {
           &quot;:&quot; =&gt; Ok(StartDefinition),
           &quot;;&quot; =&gt; Ok(EndDefinition),
           _ =&gt; Err(()),
       }.or_else(|_| Value::from_str(s).map(Number))
           .or_else(|_| Ok(Word(s.to_ascii_lowercase())))
   }
}

impl Forth {
   pub fn new() -&gt; Forth {
       Forth {
           code: LinkedList::new(),
           defs: HashMap::new(),
           stack: LinkedList::new(),
       }
   }

   pub fn stack(&amp;self) -&gt; Vec&lt;Value&gt; {
       self.stack.iter().cloned().collect()
   }

   pub fn eval(&amp;mut self, input: &amp;str) -&gt; ForthResult {
       let mut new_code = Forth::into_code(input);
       self.code.append(&amp;mut new_code);
       self.run()
   }

   fn run(&amp;mut self) -&gt; ForthResult {
       while let Some(term) = self.code.pop_front() {
           try!(self.step_term(term))
       }

       Forth::ok()
   }

   fn step_term(&amp;mut self, term: Term) -&gt; ForthResult {
       match term {
           Number(value) =&gt; self.push(value),
           Word(word) =&gt; self.step_word(word),
           StartDefinition =&gt; self.store_definition(),
           EndDefinition =&gt; Err(Error::InvalidWord),
       }
   }

   fn step_word(&amp;mut self, word: String) -&gt; ForthResult {
       self.defs
           .get(&amp;word)
           .ok_or(Error::UnknownWord)
           .map(Clone::clone)
           .map(|mut code| self.code.append(&amp;mut code))
           .or_else(|_| self.step_built_in(&amp;word))
   }

   fn step_built_in(&amp;mut self, word: &amp;String) -&gt; ForthResult {
       match word.as_ref() {
           &quot;+&quot; =&gt; self.bin_op(|(a, b)| Ok(a + b)),
           &quot;-&quot; =&gt; self.bin_op(|(a, b)| Ok(a - b)),
           &quot;*&quot; =&gt; self.bin_op(|(a, b)| Ok(a * b)),
           &quot;/&quot; =&gt; self.bin_op(|(a, b)| a.checked_div(b).ok_or(Error::DivisionByZero)),
           &quot;dup&quot; =&gt; self.pop().and_then(|a| self.push(a).and(self.push(a))),
           &quot;drop&quot; =&gt; self.pop().and(Forth::ok()),
           &quot;swap&quot; =&gt; self.pop_two()
               .and_then(|(a, b)| self.push(b).and(self.push(a))),
           &quot;over&quot; =&gt; self.pop_two()
               .and_then(|(a, b)| self.push(a).and(self.push(b)).and(self.push(a))),
           _ =&gt; Err(Error::UnknownWord),
       }
   }

   fn store_definition(&amp;mut self) -&gt; ForthResult {
       let mut def = LinkedList::new();

       loop {
           match self.code.pop_front() {
               Some(EndDefinition) =&gt; break,
               Some(term) =&gt; def.push_back(term),
               None =&gt; return Err(Error::InvalidWord),
           }
       }

       if let Some(Word(name)) = def.pop_front() {
           self.store_word(name, def)
       } else {
           Err(Error::InvalidWord)
       }
   }

   fn push(&amp;mut self, value: Value) -&gt; ForthResult {
       self.stack.push_back(value);
       Forth::ok()
   }

   fn pop(&amp;mut self) -&gt; StackResult&lt;Value&gt; {
       self.stack.pop_back().ok_or(Error::StackUnderflow)
   }

   fn pop_two(&amp;mut self) -&gt; StackResult&lt;(Value, Value)&gt; {
       self.pop().and_then(|b| self.pop().and_then(|a| Ok((a, b))))
   }

   fn bin_op&lt;F&gt;(&amp;mut self, op: F) -&gt; ForthResult
   where
       F: FnOnce((Value, Value)) -&gt; StackResult&lt;Value&gt;,
   {
       self.pop_two()
           .and_then(op)
           .and_then(|value| self.push(value))
   }

   fn store_word(&amp;mut self, name: String, code: Code) -&gt; ForthResult {
       self.defs.insert(name, code);
       Forth::ok()
   }

   fn into_code(input: &amp;str) -&gt; LinkedList&lt;Term&gt; {
       input
           .split(|c: char| c.is_whitespace() || c.is_control())
           .map(Term::from_str)
           .filter(Result::is_ok)
           .map(Result::unwrap)
           .collect()
   }

   fn ok() -&gt; ForthResult {
       Ok(())
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-85" id="填充相关-85"><h2>填充/相关</h2></a>
<a class="header" href="#circular-buffer" id="circular-buffer"><h1>Circular Buffer</h1></a>
<a class="header" href="#1-readme-86" id="1-readme-86"><h2>1. Readme</h2></a>
<a class="header" href="#循环缓冲区" id="循环缓冲区"><h1>循环缓冲区</h1></a>
<p>循环缓冲区，或环形缓冲区是一种数据结构，它使用单个固定大小的缓冲区，就好像它是端到端连接一样。</p>
<p>循环缓冲区首先开始为空，并具有一些预定义的长度。例如，这是一个 7 元素的缓冲区:</p>
<pre><code>[ ][ ][ ][ ][ ][ ][ ]
</code></pre>
<p>假设 1 被写入缓冲区的中间(其实精确的起始位置在循环缓冲区中无关紧要):</p>
<pre><code>[ ][ ][ ][1][ ][ ][ ]
</code></pre>
<p>然后假设添加了另外两个元素 - 2 和 3 - 在 1 之后，附加:</p>
<pre><code>[ ][ ][ ][1][2][3][ ]
</code></pre>
<p>如果从缓冲区中，删除了两个元素，则删除缓冲区内最旧的值。在这种情况下，删除的两个元素是 1 和 2，缓冲区只有 3:</p>
<pre><code>[ ][ ][ ][ ][ ][3][ ]
</code></pre>
<p>如果缓冲区有 7 个元素，那么它就完全填满了:</p>
<pre><code>[6][7][8][9][3][4][5]
</code></pre>
<p>当缓冲区已满时，将引发错误，警告客户端，进一步写入被阻止，直到插槽空闲为止。</p>
<p>当缓冲区已满时，客户端可以选择使用强制写入，覆盖最旧的数据。在这种情况下，添加了另外两个元素 - A 和 B - 它们会覆盖 3 和 4:</p>
<pre><code>[6][7][8][9][A][B][5]

</code></pre>
<p>3 和 4 已被 A 和 B 取代，使得 5 现在是缓冲区中最旧的数据。最后，如果删除了两个元素，那么返回的是 5 和 6，和剩余的缓冲区:</p>
<pre><code>
[ ][7][8][9][A][B][ ]

</code></pre>
<p>因为有可用的空间，但如果客户端再次覆盖存储 C 和 D，那么先前存储 5 和 6 的空间将被使用，而不是 7 和 8 的位置。7 仍然是最旧的元素，缓冲区又是充分.</p>
<pre><code>[D][7][8][9][A][B][C]
</code></pre>
<a class="header" href="#资源-64" id="资源-64"><h2>资源</h2></a>
<p>维基百科<a href="http://en.wikipedia.org/wiki/Circular_Buffer">http://en.wikipedia.org/wiki/Circular_Buffer</a></p>
<a class="header" href="#2-开始你的表演-86" id="2-开始你的表演-86"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">use std::marker::PhantomData;

pub struct CircularBuffer&lt;T&gt; {
   // This field is here to make the template compile and not to
   // complain about unused type parameter 'T'. Once you start
   // solving the exercise, delete this field and the 'std::marker::PhantomData'
   // import.
   field: PhantomData&lt;T&gt;,
}

#[derive(Debug, PartialEq)]
pub enum Error {
   EmptyBuffer,
   FullBuffer,
}

impl&lt;T&gt; CircularBuffer&lt;T&gt; {
   pub fn new(capacity: usize) -&gt; Self {
       unimplemented!(
           &quot;Construct a new CircularBuffer with the capacity to hold {}.&quot;,
           match capacity {
               1 =&gt; format!(&quot;1 element&quot;),
               _ =&gt; format!(&quot;{} elements&quot;, capacity),
           }
       );
   }

   pub fn write(&amp;mut self, _element: T) -&gt; Result&lt;(), Error&gt; {
       unimplemented!(&quot;Write the passed element to the CircularBuffer or return FullBuffer error if CircularBuffer is full.&quot;);
   }

   pub fn read(&amp;mut self) -&gt; Result&lt;T, Error&gt; {
       unimplemented!(&quot;Read the oldest element from the CircularBuffer or return EmptyBuffer error if CircularBuffer is empty.&quot;);
   }

   pub fn clear(&amp;mut self) {
       unimplemented!(&quot;Clear the CircularBuffer.&quot;);
   }

   pub fn overwrite(&amp;mut self, _element: T) {
       unimplemented!(&quot;Write the passed element to the CircularBuffer, overwriting the existing elements if CircularBuffer is full.&quot;);
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-86" id="3-测试代码查看-86"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn error_on_read_empty_buffer() {
   let mut buffer = CircularBuffer::&lt;char&gt;::new(1);
   assert_eq!(Err(Error::EmptyBuffer), buffer.read());
}

#[test]
//#[ignore]
fn write_and_read_back_item() {
   let mut buffer = CircularBuffer::new(1);
   assert!(buffer.write('1').is_ok());
   assert_eq!(Ok('1'), buffer.read());
   assert_eq!(Err(Error::EmptyBuffer), buffer.read());
}

#[test]
//#[ignore]
fn write_and_read_back_multiple_items() {
   let mut buffer = CircularBuffer::new(2);
   assert!(buffer.write('1').is_ok());
   assert!(buffer.write('2').is_ok());
   assert_eq!(Ok('1'), buffer.read());
   assert_eq!(Ok('2'), buffer.read());
   assert_eq!(Err(Error::EmptyBuffer), buffer.read());
}

#[test]
//#[ignore]
fn alternate_write_and_read() {
   let mut buffer = CircularBuffer::new(2);
   assert!(buffer.write('1').is_ok());
   assert_eq!(Ok('1'), buffer.read());
   assert!(buffer.write('2').is_ok());
   assert_eq!(Ok('2'), buffer.read());
}

#[test]
//#[ignore]
fn clear_buffer() {
   let mut buffer = CircularBuffer::new(3);
   assert!(buffer.write('1').is_ok());
   assert!(buffer.write('2').is_ok());
   assert!(buffer.write('3').is_ok());
   buffer.clear();
   assert_eq!(Err(Error::EmptyBuffer), buffer.read());
   assert!(buffer.write('1').is_ok());
   assert!(buffer.write('2').is_ok());
   assert_eq!(Ok('1'), buffer.read());
   assert!(buffer.write('3').is_ok());
   assert_eq!(Ok('2'), buffer.read());
}

#[test]
//#[ignore]
fn full_buffer_error() {
   let mut buffer = CircularBuffer::new(2);
   assert!(buffer.write('1').is_ok());
   assert!(buffer.write('2').is_ok());
   assert_eq!(Err(Error::FullBuffer), buffer.write('3'));
}

#[test]
//#[ignore]
fn overwrite_item_in_non_full_buffer() {
   let mut buffer = CircularBuffer::new(2);
   assert!(buffer.write('1').is_ok());
   buffer.overwrite('2');
   assert_eq!(Ok('1'), buffer.read());
   assert_eq!(Ok('2'), buffer.read());
   assert_eq!(Err(Error::EmptyBuffer), buffer.read());
}

#[test]
//#[ignore]
fn overwrite_item_in_full_buffer() {
   let mut buffer = CircularBuffer::new(2);
   assert!(buffer.write('1').is_ok());
   assert!(buffer.write('2').is_ok());
   buffer.overwrite('A');
   assert_eq!(Ok('2'), buffer.read());
   assert_eq!(Ok('A'), buffer.read());
}

#[test]
//#[ignore]
fn integer_buffer() {
   let mut buffer = CircularBuffer::new(2);
   assert!(buffer.write(1).is_ok());
   assert!(buffer.write(2).is_ok());
   assert_eq!(Ok(1), buffer.read());
   assert!(buffer.write(-1).is_ok());
   assert_eq!(Ok(2), buffer.read());
   assert_eq!(Ok(-1), buffer.read());
   assert_eq!(Err(Error::EmptyBuffer), buffer.read());
}

#[test]
//#[ignore]
fn string_buffer() {
   let mut buffer = CircularBuffer::new(2);
   buffer.write(&quot;&quot;.to_string()).unwrap();
   buffer.write(&quot;Testing&quot;.to_string()).unwrap();
   assert_eq!(0, buffer.read().unwrap().len());
   assert_eq!(Ok(&quot;Testing&quot;.to_string()), buffer.read());
}

#}</code></pre></pre>
<a class="header" href="#4-答案-86" id="4-答案-86"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[derive(Debug, PartialEq)]
pub enum Error {
   EmptyBuffer,
   FullBuffer,
}

pub struct CircularBuffer&lt;T: Default + Clone&gt; {
   buffer: Vec&lt;T&gt;,
   size: usize,
   start: usize,
   end: usize,
}

impl&lt;T: Default + Clone&gt; CircularBuffer&lt;T&gt; {
   // this circular buffer keeps an unallocated slot between the start and the end
   // when the buffer is full.
   pub fn new(size: usize) -&gt; CircularBuffer&lt;T&gt; {
       CircularBuffer {
           buffer: vec![T::default(); size + 1],
           size: size + 1,
           start: 0,
           end: 0,
       }
   }

   pub fn read(&amp;mut self) -&gt; Result&lt;T, Error&gt; {
       if self.is_empty() {
           return Err(Error::EmptyBuffer);
       }

       let v = self.buffer.get(self.start).unwrap().clone();
       self.advance_start();
       Ok(v)
   }

   pub fn write(&amp;mut self, byte: T) -&gt; Result&lt;(), Error&gt; {
       if self.is_full() {
           return Err(Error::FullBuffer);
       }

       self.buffer[self.end] = byte;
       self.advance_end();
       Ok(())
   }

   pub fn overwrite(&amp;mut self, byte: T) {
       if self.is_full() {
           self.advance_start();
       }

       self.buffer[self.end] = byte;
       self.advance_end();
   }

   pub fn clear(&amp;mut self) {
       self.start = 0;
       self.end = 0;
   }

   pub fn is_empty(&amp;self) -&gt; bool {
       self.start == self.end
   }

   pub fn is_full(&amp;self) -&gt; bool {
       (self.end + 1) % self.size == self.start
   }

   fn advance_start(&amp;mut self) {
       self.start = (self.start + 1) % self.size;
   }

   fn advance_end(&amp;mut self) {
       self.end = (self.end + 1) % self.size;
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-86" id="填充相关-86"><h2>填充/相关</h2></a>
<a class="header" href="#react" id="react"><h1>React</h1></a>
<a class="header" href="#1-readme-87" id="1-readme-87"><h2>1. Readme</h2></a>
<a class="header" href="#react-1" id="react-1"><h1>React</h1></a>
<p>实现基本的 React 系统。</p>
<p>React 式编程是一种编程范例，它着重于如何根据彼此来计算值，以允许对一个值的更改，自动传播到其他值，如在电子表格中。</p>
<p>实现一个基本的 React 系统，其中，有带可设置值的单元(”输入”单元)，还有能根据其他单元计算值的单元(”计算”单元)。实现更新，以便当输入值改变时，（关联的）值会传播，直到一个新的稳定的系统状态。</p>
<p>此外，计算单元应该允许，注册更改通知的回调。当单元值，从之前的稳定状态到一个新的稳定状态时，调用一个单元格的回调。</p>
<a class="header" href="#2-开始你的表演-87" id="2-开始你的表演-87"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">/// `InputCellID` is a unique identifier for an input cell.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct InputCellID();
/// `ComputeCellID` is a unique identifier for a compute cell.
/// Values of type `InputCellID` and `ComputeCellID` should not be mutually assignable,
/// demonstrated by the following tests:
///
/// ```compile_fail
/// let mut r = react::Reactor::new();
/// let input: react::ComputeCellID = r.create_input(111);
/// ```
///
/// ```compile_fail
/// let mut r = react::Reactor::new();
/// let input = r.create_input(111);
/// let compute: react::InputCellID = r.create_compute(&amp;[react::CellID::Input(input)], |_| 222).unwrap();
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ComputeCellID();
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CallbackID();

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CellID {
   Input(InputCellID),
   Compute(ComputeCellID),
}

#[derive(Debug, PartialEq)]
pub enum RemoveCallbackError {
   NonexistentCell,
   NonexistentCallback,
}

pub struct Reactor&lt;T&gt; {
   // Just so that the compiler doesn't complain about an unused type parameter.
   // You probably want to delete this field.
   dummy: ::std::marker::PhantomData&lt;T&gt;,
}

// You are guaranteed that Reactor will only be tested against types that are Copy + PartialEq.
impl&lt;T: Copy + PartialEq&gt; Reactor&lt;T&gt; {
   pub fn new() -&gt; Self {
       unimplemented!()
   }

   // Creates an input cell with the specified initial value, returning its ID.
   pub fn create_input(&amp;mut self, _initial: T) -&gt; InputCellID {
       unimplemented!()
   }

   // Creates a compute cell with the specified dependencies and compute function.
   // The compute function is expected to take in its arguments in the same order as specified in
   // `dependencies`.
   // You do not need to reject compute functions that expect more arguments than there are
   // dependencies (how would you check for this, anyway?).
   //
   // If any dependency doesn't exist, returns an Err with that nonexistent dependency.
   // (If multiple dependencies do not exist, exactly which one is returned is not defined and
   // will not be tested)
   //
   // Notice that there is no way to *remove* a cell.
   // This means that you may assume, without checking, that if the dependencies exist at creation
   // time they will continue to exist as long as the Reactor exists.
   pub fn create_compute&lt;F: Fn(&amp;[T]) -&gt; T&gt;(
       &amp;mut self,
       _dependencies: &amp;[CellID],
       _compute_func: F,
   ) -&gt; Result&lt;ComputeCellID, CellID&gt; {
       unimplemented!()
   }

   // Retrieves the current value of the cell, or None if the cell does not exist.
   //
   // You may wonder whether it is possible to implement `get(&amp;self, id: CellID) -&gt; Option&lt;&amp;Cell&gt;`
   // and have a `value(&amp;self)` method on `Cell`.
   //
   // It turns out this introduces a significant amount of extra complexity to this exercise.
   // We chose not to cover this here, since this exercise is probably enough work as-is.
   pub fn value(&amp;self, id: CellID) -&gt; Option&lt;T&gt; {
       unimplemented!(&quot;Get the value of the cell whose id is {:?}&quot;, id)
   }

   // Sets the value of the specified input cell.
   //
   // Returns false if the cell does not exist.
   //
   // Similarly, you may wonder about `get_mut(&amp;mut self, id: CellID) -&gt; Option&lt;&amp;mut Cell&gt;`, with
   // a `set_value(&amp;mut self, new_value: T)` method on `Cell`.
   //
   // As before, that turned out to add too much extra complexity.
   pub fn set_value(&amp;mut self, _id: InputCellID, _new_value: T) -&gt; bool {
       unimplemented!()
   }

   // Adds a callback to the specified compute cell.
   //
   // Returns the ID of the just-added callback, or None if the cell doesn't exist.
   //
   // Callbacks on input cells will not be tested.
   //
   // The semantics of callbacks (as will be tested):
   // For a single set_value call, each compute cell's callbacks should each be called:
   // * Zero times if the compute cell's value did not change as a result of the set_value call.
   // * Exactly once if the compute cell's value changed as a result of the set_value call.
   //   The value passed to the callback should be the final value of the compute cell after the
   //   set_value call.
   pub fn add_callback&lt;F: FnMut(T) -&gt; ()&gt;(
       &amp;mut self,
       _id: ComputeCellID,
       _callback: F,
   ) -&gt; Option&lt;CallbackID&gt; {
       unimplemented!()
   }

   // Removes the specified callback, using an ID returned from add_callback.
   //
   // Returns an Err if either the cell or callback does not exist.
   //
   // A removed callback should no longer be called.
   pub fn remove_callback(
       &amp;mut self,
       cell: ComputeCellID,
       callback: CallbackID,
   ) -&gt; Result&lt;(), RemoveCallbackError&gt; {
       unimplemented!(
           &quot;Remove the callback identified by the CallbackID {:?} from the cell {:?}&quot;,
           callback,
           cell,
       )
   }
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-87" id="3-测试代码查看-87"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn input_cells_have_a_value() {
   let mut reactor = Reactor::new();
   let input = reactor.create_input(10);
   assert_eq!(reactor.value(CellID::Input(input)), Some(10));
}

#[test]
//#[ignore]
fn an_input_cells_value_can_be_set() {
   let mut reactor = Reactor::new();
   let input = reactor.create_input(4);
   assert!(reactor.set_value(input, 20));
   assert_eq!(reactor.value(CellID::Input(input)), Some(20));
}

#[test]
//#[ignore]
fn error_setting_a_nonexistent_input_cell() {
   let mut dummy_reactor = Reactor::new();
   let input = dummy_reactor.create_input(1);
   assert!(!Reactor::new().set_value(input, 0));
}

#[test]
//#[ignore]
fn compute_cells_calculate_initial_value() {
   let mut reactor = Reactor::new();
   let input = reactor.create_input(1);
   let output = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] + 1)
       .unwrap();
   assert_eq!(reactor.value(CellID::Compute(output)), Some(2));
}

#[test]
//#[ignore]
fn compute_cells_take_inputs_in_the_right_order() {
   let mut reactor = Reactor::new();
   let one = reactor.create_input(1);
   let two = reactor.create_input(2);
   let output = reactor
       .create_compute(&amp;[CellID::Input(one), CellID::Input(two)], |v| {
           v[0] + v[1] * 10
       })
       .unwrap();
   assert_eq!(reactor.value(CellID::Compute(output)), Some(21));
}

#[test]
//#[ignore]
fn error_creating_compute_cell_if_input_doesnt_exist() {
   let mut dummy_reactor = Reactor::new();
   let input = dummy_reactor.create_input(1);
   assert_eq!(
       Reactor::new().create_compute(&amp;[CellID::Input(input)], |_| 0),
       Err(CellID::Input(input))
   );
}

#[test]
//#[ignore]
fn do_not_break_cell_if_creating_compute_cell_with_valid_and_invalid_input() {
   let mut dummy_reactor = Reactor::new();
   let _ = dummy_reactor.create_input(1);
   let dummy_cell = dummy_reactor.create_input(2);
   let mut reactor = Reactor::new();
   let input = reactor.create_input(1);
   assert_eq!(
       reactor.create_compute(&amp;[CellID::Input(input), CellID::Input(dummy_cell)], |_| 0),
       Err(CellID::Input(dummy_cell))
   );
   assert!(reactor.set_value(input, 5));
   assert_eq!(reactor.value(CellID::Input(input)), Some(5));
}

#[test]
//#[ignore]
fn compute_cells_update_value_when_dependencies_are_changed() {
   let mut reactor = Reactor::new();
   let input = reactor.create_input(1);
   let output = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] + 1)
       .unwrap();
   assert_eq!(reactor.value(CellID::Compute(output)), Some(2));
   assert!(reactor.set_value(input, 3));
   assert_eq!(reactor.value(CellID::Compute(output)), Some(4));
}

#[test]
//#[ignore]
fn compute_cells_can_depend_on_other_compute_cells() {
   let mut reactor = Reactor::new();
   let input = reactor.create_input(1);
   let times_two = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] * 2)
       .unwrap();
   let times_thirty = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] * 30)
       .unwrap();
   let output = reactor
       .create_compute(
           &amp;[CellID::Compute(times_two), CellID::Compute(times_thirty)],
           |v| v[0] + v[1],
       )
       .unwrap();
   assert_eq!(reactor.value(CellID::Compute(output)), Some(32));
   assert!(reactor.set_value(input, 3));
   assert_eq!(reactor.value(CellID::Compute(output)), Some(96));
}

/// A CallbackRecorder helps tests whether callbacks get called correctly.
/// You'll see it used in tests that deal with callbacks.
/// The names should be descriptive enough so that the tests make sense,
/// so it's not necessary to fully understand the implementation,
/// though you are welcome to.
struct CallbackRecorder {
   // Note that this `Cell` is https://doc.rust-lang.org/std/cell/
   // a mechanism to allow internal mutability,
   // distinct from the cells (input cells, compute cells) in the reactor
   value: std::cell::Cell&lt;Option&lt;i32&gt;&gt;,
}

impl CallbackRecorder {
   fn new() -&gt; Self {
       CallbackRecorder {
           value: std::cell::Cell::new(None),
       }
   }

   fn expect_to_have_been_called_with(&amp;self, v: i32) {
       assert_ne!(
           self.value.get(),
           None,
           &quot;Callback was not called, but should have been&quot;
       );
       assert_eq!(
           self.value.replace(None),
           Some(v),
           &quot;Callback was called with incorrect value&quot;
       );
   }

   fn expect_not_to_have_been_called(&amp;self) {
       assert_eq!(
           self.value.get(),
           None,
           &quot;Callback was called, but should not have been&quot;
       );
   }

   fn callback_called(&amp;self, v: i32) {
       assert_eq!(
           self.value.replace(Some(v)),
           None,
           &quot;Callback was called too many times; can't be called with {}&quot;,
           v
       );
   }
}

#[test]
//#[ignore]
fn compute_cells_fire_callbacks() {
   let cb = CallbackRecorder::new();
   let mut reactor = Reactor::new();
   let input = reactor.create_input(1);
   let output = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] + 1)
       .unwrap();
   assert!(reactor
       .add_callback(output, |v| cb.callback_called(v))
       .is_some());
   assert!(reactor.set_value(input, 3));
   cb.expect_to_have_been_called_with(4);
}

#[test]
//#[ignore]
fn error_adding_callback_to_nonexistent_cell() {
   let mut dummy_reactor = Reactor::new();
   let input = dummy_reactor.create_input(1);
   let output = dummy_reactor
       .create_compute(&amp;[CellID::Input(input)], |_| 0)
       .unwrap();
   assert_eq!(
       Reactor::new().add_callback(output, |_: u32| println!(&quot;hi&quot;)),
       None
   );
}

#[test]
//#[ignore]
fn callbacks_only_fire_on_change() {
   let cb = CallbackRecorder::new();
   let mut reactor = Reactor::new();
   let input = reactor.create_input(1);
   let output = reactor
       .create_compute(
           &amp;[CellID::Input(input)],
           |v| if v[0] &lt; 3 { 111 } else { 222 },
       )
       .unwrap();
   assert!(reactor
       .add_callback(output, |v| cb.callback_called(v))
       .is_some());

   assert!(reactor.set_value(input, 2));
   cb.expect_not_to_have_been_called();
   assert!(reactor.set_value(input, 4));
   cb.expect_to_have_been_called_with(222);
}

#[test]
//#[ignore]
fn callbacks_can_be_added_and_removed() {
   let cb1 = CallbackRecorder::new();
   let cb2 = CallbackRecorder::new();
   let cb3 = CallbackRecorder::new();

   let mut reactor = Reactor::new();
   let input = reactor.create_input(11);
   let output = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] + 1)
       .unwrap();

   let callback = reactor
       .add_callback(output, |v| cb1.callback_called(v))
       .unwrap();
   assert!(reactor
       .add_callback(output, |v| cb2.callback_called(v))
       .is_some());

   assert!(reactor.set_value(input, 31));
   cb1.expect_to_have_been_called_with(32);
   cb2.expect_to_have_been_called_with(32);

   assert!(reactor.remove_callback(output, callback).is_ok());
   assert!(reactor
       .add_callback(output, |v| cb3.callback_called(v))
       .is_some());

   assert!(reactor.set_value(input, 41));
   cb1.expect_not_to_have_been_called();
   cb2.expect_to_have_been_called_with(42);
   cb3.expect_to_have_been_called_with(42);
}

#[test]
//#[ignore]
fn removing_a_callback_multiple_times_doesnt_interfere_with_other_callbacks() {
   let cb1 = CallbackRecorder::new();
   let cb2 = CallbackRecorder::new();

   let mut reactor = Reactor::new();
   let input = reactor.create_input(1);
   let output = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] + 1)
       .unwrap();
   let callback = reactor
       .add_callback(output, |v| cb1.callback_called(v))
       .unwrap();
   assert!(reactor
       .add_callback(output, |v| cb2.callback_called(v))
       .is_some());
   // We want the first remove to be Ok, but the others should be errors.
   assert!(reactor.remove_callback(output, callback).is_ok());
   for _ in 1..5 {
       assert_eq!(
           reactor.remove_callback(output, callback),
           Err(RemoveCallbackError::NonexistentCallback)
       );
   }

   assert!(reactor.set_value(input, 2));
   cb1.expect_not_to_have_been_called();
   cb2.expect_to_have_been_called_with(3);
}

#[test]
//#[ignore]
fn callbacks_should_only_be_called_once_even_if_multiple_dependencies_change() {
   let cb = CallbackRecorder::new();
   let mut reactor = Reactor::new();
   let input = reactor.create_input(1);
   let plus_one = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] + 1)
       .unwrap();
   let minus_one1 = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] - 1)
       .unwrap();
   let minus_one2 = reactor
       .create_compute(&amp;[CellID::Compute(minus_one1)], |v| v[0] - 1)
       .unwrap();
   let output = reactor
       .create_compute(
           &amp;[CellID::Compute(plus_one), CellID::Compute(minus_one2)],
           |v| v[0] * v[1],
       )
       .unwrap();
   assert!(reactor
       .add_callback(output, |v| cb.callback_called(v))
       .is_some());
   assert!(reactor.set_value(input, 4));
   cb.expect_to_have_been_called_with(10);
}

#[test]
//#[ignore]
fn callbacks_should_not_be_called_if_dependencies_change_but_output_value_doesnt_change() {
   let cb = CallbackRecorder::new();
   let mut reactor = Reactor::new();
   let input = reactor.create_input(1);
   let plus_one = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] + 1)
       .unwrap();
   let minus_one = reactor
       .create_compute(&amp;[CellID::Input(input)], |v| v[0] - 1)
       .unwrap();
   let always_two = reactor
       .create_compute(
           &amp;[CellID::Compute(plus_one), CellID::Compute(minus_one)],
           |v| v[0] - v[1],
       )
       .unwrap();
   assert!(reactor
       .add_callback(always_two, |v| cb.callback_called(v))
       .is_some());
   for i in 2..5 {
       assert!(reactor.set_value(input, i));
       cb.expect_not_to_have_been_called();
   }
}

#[test]
//#[ignore]
fn test_adder_with_boolean_values() {
   // This is a digital logic circuit called an adder:
   // https://en.wikipedia.org/wiki/Adder_(electronics)
   let mut reactor = Reactor::new();
   let a = reactor.create_input(false);
   let b = reactor.create_input(false);
   let carry_in = reactor.create_input(false);

   let a_xor_b = reactor
       .create_compute(&amp;[CellID::Input(a), CellID::Input(b)], |v| v[0] ^ v[1])
       .unwrap();
   let sum = reactor
       .create_compute(&amp;[CellID::Compute(a_xor_b), CellID::Input(carry_in)], |v| {
           v[0] ^ v[1]
       })
       .unwrap();

   let a_xor_b_and_cin = reactor
       .create_compute(&amp;[CellID::Compute(a_xor_b), CellID::Input(carry_in)], |v| {
           v[0] &amp;&amp; v[1]
       })
       .unwrap();
   let a_and_b = reactor
       .create_compute(&amp;[CellID::Input(a), CellID::Input(b)], |v| v[0] &amp;&amp; v[1])
       .unwrap();
   let carry_out = reactor
       .create_compute(
           &amp;[CellID::Compute(a_xor_b_and_cin), CellID::Compute(a_and_b)],
           |v| v[0] || v[1],
       )
       .unwrap();

   let tests = &amp;[
       (false, false, false, false, false),
       (false, false, true, false, true),
       (false, true, false, false, true),
       (false, true, true, true, false),
       (true, false, false, false, true),
       (true, false, true, true, false),
       (true, true, false, true, false),
       (true, true, true, true, true),
   ];

   for &amp;(aval, bval, cinval, expected_cout, expected_sum) in tests {
       assert!(reactor.set_value(a, aval));
       assert!(reactor.set_value(b, bval));
       assert!(reactor.set_value(carry_in, cinval));

       assert_eq!(reactor.value(CellID::Compute(sum)), Some(expected_sum));
       assert_eq!(
           reactor.value(CellID::Compute(carry_out)),
           Some(expected_cout)
       );
   }
}

#}</code></pre></pre>
<a class="header" href="#4-答案-87" id="4-答案-87"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;

/// `InputCellID` is a unique identifier for an input cell.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct InputCellID(usize);
/// `ComputeCellID` is a unique identifier for a compute cell.
/// Values of type `InputCellID` and `ComputeCellID` should not be mutually assignable,
/// demonstrated by the following tests:
///
/// ```compile_fail
/// let mut r = react::Reactor::new();
/// let input: react::ComputeCellID = r.create_input(111);
/// ```
///
/// ```compile_fail
/// let mut r = react::Reactor::new();
/// let input = r.create_input(111);
/// let compute: react::InputCellID = r.create_compute(&amp;[react::CellID::Input(input)], |_| 222).unwrap();
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ComputeCellID(usize);
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct CallbackID(usize);

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CellID {
   Input(InputCellID),
   Compute(ComputeCellID),
}

#[derive(Debug, PartialEq)]
pub enum RemoveCallbackError {
   NonexistentCell,
   NonexistentCallback,
}

struct Cell&lt;T: Copy&gt; {
   value: T,
   last_value: T,
   dependents: Vec&lt;ComputeCellID&gt;,
}

struct ComputeCell&lt;'a, T: Copy&gt; {
   cell: Cell&lt;T&gt;,

   dependencies: Vec&lt;CellID&gt;,
   f: Box&lt;Fn(&amp;[T]) -&gt; T + 'a&gt;,
   callbacks_issued: usize,
   callbacks: HashMap&lt;CallbackID, Box&lt;FnMut(T) -&gt; () + 'a&gt;&gt;,
}

impl&lt;T: Copy&gt; Cell&lt;T&gt; {
   fn new(initial: T) -&gt; Self {
       Cell {
           value: initial,
           last_value: initial,
           dependents: Vec::new(),
       }
   }
}

impl&lt;'a, T: Copy&gt; ComputeCell&lt;'a, T&gt; {
   fn new&lt;F: Fn(&amp;[T]) -&gt; T + 'a&gt;(initial: T, dependencies: Vec&lt;CellID&gt;, f: F) -&gt; Self {
       ComputeCell {
           cell: Cell::new(initial),

           dependencies,
           f: Box::new(f),
           callbacks_issued: 0,
           callbacks: HashMap::new(),
       }
   }
}

pub struct Reactor&lt;'a, T: Copy&gt; {
   inputs: Vec&lt;Cell&lt;T&gt;&gt;,
   computes: Vec&lt;ComputeCell&lt;'a, T&gt;&gt;,
}

impl&lt;'a, T: Copy + PartialEq&gt; Reactor&lt;'a, T&gt; {
   pub fn new() -&gt; Self {
       Reactor {
           inputs: Vec::new(),
           computes: Vec::new(),
       }
   }

   pub fn create_input(&amp;mut self, initial: T) -&gt; InputCellID {
       self.inputs.push(Cell::new(initial));
       InputCellID(self.inputs.len() - 1)
   }

   pub fn create_compute&lt;F: Fn(&amp;[T]) -&gt; T + 'a&gt;(
       &amp;mut self,
       dependencies: &amp;[CellID],
       compute_func: F,
   ) -&gt; Result&lt;ComputeCellID, CellID&gt; {
       // Check all dependencies' validity before modifying any of them,
       // so that we don't perform an incorrect partial write.
       for &amp;dep in dependencies {
           match dep {
               CellID::Input(InputCellID(id)) =&gt; if id &gt;= self.inputs.len() {
                   return Err(dep);
               },
               CellID::Compute(ComputeCellID(id)) =&gt; if id &gt;= self.computes.len() {
                   return Err(dep);
               },
           }
       }
       let new_id = ComputeCellID(self.computes.len());
       for &amp;dep in dependencies {
           match dep {
               CellID::Input(InputCellID(id)) =&gt; self.inputs[id].dependents.push(new_id),
               CellID::Compute(ComputeCellID(id)) =&gt; {
                   self.computes[id].cell.dependents.push(new_id)
               }
           }
       }
       let inputs: Vec&lt;_&gt; = dependencies
           .iter()
           .map(|&amp;id| self.value(id).unwrap())
           .collect();
       let initial = compute_func(&amp;inputs);
       self.computes.push(ComputeCell::new(
           initial,
           dependencies.to_vec(),
           compute_func,
       ));
       Ok(new_id)
   }

   pub fn value(&amp;self, id: CellID) -&gt; Option&lt;T&gt; {
       match id {
           CellID::Input(InputCellID(id)) =&gt; self.inputs.get(id).map(|c| c.value),
           CellID::Compute(ComputeCellID(id)) =&gt; self.computes.get(id).map(|c| c.cell.value),
       }
   }

   pub fn set_value(&amp;mut self, id: InputCellID, new_value: T) -&gt; bool {
       let InputCellID(id) = id;
       self.inputs
           .get_mut(id)
           .map(|c| {
               c.value = new_value;
               c.dependents.clone()
           })
           .map(|deps| {
               for &amp;d in deps.iter() {
                   self.update_dependent(d);
               }
               // We can only fire callbacks after all dependents have updated.
               // So we can't combine this for loop with the one above!
               for d in deps {
                   self.fire_callbacks(d);
               }
           })
           .is_some()
   }

   pub fn add_callback&lt;F: FnMut(T) -&gt; () + 'a&gt;(
       &amp;mut self,
       id: ComputeCellID,
       callback: F,
   ) -&gt; Option&lt;CallbackID&gt; {
       let ComputeCellID(id) = id;
       self.computes.get_mut(id).map(|c| {
           c.callbacks_issued += 1;
           let cbid = CallbackID(c.callbacks_issued);
           c.callbacks.insert(cbid, Box::new(callback));
           cbid
       })
   }

   pub fn remove_callback(
       &amp;mut self,
       cell: ComputeCellID,
       callback: CallbackID,
   ) -&gt; Result&lt;(), RemoveCallbackError&gt; {
       let ComputeCellID(cell) = cell;
       match self.computes.get_mut(cell) {
           Some(c) =&gt; match c.callbacks.remove(&amp;callback) {
               Some(_) =&gt; Ok(()),
               None =&gt; Err(RemoveCallbackError::NonexistentCallback),
           },
           None =&gt; Err(RemoveCallbackError::NonexistentCell),
       }
   }

   fn update_dependent(&amp;mut self, id: ComputeCellID) {
       let ComputeCellID(id) = id;

       let (new_value, dependents) = {
           // This block limits the scope of the self.cells borrow.
           // This is necessary because we borrow it mutably below.
           let (dependencies, f, dependents) = match self.computes.get(id) {
               Some(c) =&gt; (&amp;c.dependencies, &amp;c.f, c.cell.dependents.clone()),
               None =&gt; panic!(&quot;Cell to update disappeared while querying&quot;),
           };
           let inputs: Vec&lt;_&gt; = dependencies
               .iter()
               .map(|&amp;id| self.value(id).unwrap())
               .collect();
           (f(&amp;inputs), dependents)
       };

       match self.computes.get_mut(id) {
           Some(c) =&gt; {
               if c.cell.value == new_value {
                   // No change here, we don't need to update our dependents.
                   // (It wouldn't hurt to, but it would be unnecessary work)
                   return;
               }
               c.cell.value = new_value;
           }
           None =&gt; panic!(&quot;Cell to update disappeared while updating&quot;),
       }

       for d in dependents {
           self.update_dependent(d);
       }
   }

   fn fire_callbacks(&amp;mut self, id: ComputeCellID) {
       let ComputeCellID(id) = id;
       let dependents = match self.computes.get_mut(id) {
           Some(c) =&gt; {
               if c.cell.value == c.cell.last_value {
                   // Value hasn't changed since last callback fire.
                   // We thus shouldn't fire the callbacks.
                   return;
               }
               for cb in c.callbacks.values_mut() {
                   cb(c.cell.value);
               }
               c.cell.last_value = c.cell.value;
               c.cell.dependents.clone()
           }
           None =&gt; panic!(&quot;Callback cell disappeared&quot;),
       };

       for d in dependents {
           self.fire_callbacks(d);
       }
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-87" id="填充相关-87"><h2>填充/相关</h2></a>
<a class="header" href="#未标签" id="未标签"><h1>未标签</h1></a>
<ul>
<li><a href="./hexadecimal/README.zh.html">hexadecimal</a></li>
<li><a href="./nucleotide-codons/README.zh.html">nucleotide-codons</a></li>
<li><a href="./pascals-triangle/README.zh.html">pascals-triangle</a></li>
<li><a href="./two-fer/README.zh.html">two-fer</a></li>
</ul>
<a class="header" href="#hexadecimal" id="hexadecimal"><h1>hexadecimal</h1></a>
<a class="header" href="#1-readme-88" id="1-readme-88"><h2>1. Readme</h2></a>
<a class="header" href="#十六进制" id="十六进制"><h1>十六进制</h1></a>
<p>使用第一原理，将用字符串表示的十六进制数，(例如”10af8c”)，转换为其十进制等效数(即，不可以使用内置或外部库来完成转换)。</p>
<p>在 Web 上，我们使用十六进制表示颜色，例如( green: 008000,
teal: 008080, navy: 000080)。</p>
<p>程序应该处理无效十六进制字符串。</p>
<a class="header" href="#资源-65" id="资源-65"><h2>资源</h2></a>
<p>计算机科学的所有<a href="http://www.wolframalpha.com/examples/NumberBases.html">http://www.wolframalpha.com/examples/NumberBases.html</a></p>
<a class="header" href="#2-开始你的表演-88" id="2-开始你的表演-88"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">

</code></pre></pre>
<a class="header" href="#3-测试代码查看-88" id="3-测试代码查看-88"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_hex_1_is_decimal_1() {
   assert_eq!(Some(1), hex_to_int(&quot;1&quot;));
}

#[test]
//#[ignore]
fn test_hex_c_is_decimal_12() {
   assert_eq!(Some(12), hex_to_int(&quot;c&quot;));
}

#[test]
//#[ignore]
fn test_hex_10_is_decimal_16() {
   assert_eq!(Some(16), hex_to_int(&quot;10&quot;));
}

#[test]
//#[ignore]
fn test_hex_af_is_decimal_175() {
   assert_eq!(Some(175), hex_to_int(&quot;af&quot;));
}

#[test]
//#[ignore]
fn test_hex_100_is_decimal_256() {
   assert_eq!(Some(256), hex_to_int(&quot;100&quot;));
}

#[test]
//#[ignore]
fn test_hex_19ace_is_decimal_105166() {
   assert_eq!(Some(105166), hex_to_int(&quot;19ace&quot;));
}

#[test]
//#[ignore]
fn test_invalid_hex_is_none() {
   assert_eq!(None, hex_to_int(&quot;carrot&quot;));
}

#[test]
//#[ignore]
fn test_black() {
   assert_eq!(Some(0), hex_to_int(&quot;0000000&quot;));
}

#[test]
//#[ignore]
fn test_white() {
   assert_eq!(Some(16777215), hex_to_int(&quot;ffffff&quot;));
}

#[test]
//#[ignore]
fn test_yellow() {
   assert_eq!(Some(16776960), hex_to_int(&quot;ffff00&quot;));
}

#}</code></pre></pre>
<a class="header" href="#4-答案-88" id="4-答案-88"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn parse_hex_digit(c: char) -&gt; Option&lt;i64&gt; {
   match c {
       '0' =&gt; Some(0),
       '1' =&gt; Some(1),
       '2' =&gt; Some(2),
       '3' =&gt; Some(3),
       '4' =&gt; Some(4),
       '5' =&gt; Some(5),
       '6' =&gt; Some(6),
       '7' =&gt; Some(7),
       '8' =&gt; Some(8),
       '9' =&gt; Some(9),
       'a' =&gt; Some(10),
       'b' =&gt; Some(11),
       'c' =&gt; Some(12),
       'd' =&gt; Some(13),
       'e' =&gt; Some(14),
       'f' =&gt; Some(15),
       _ =&gt; None,
   }
}

pub fn hex_to_int(string: &amp;str) -&gt; Option&lt;i64&gt; {
   let base: i64 = 16;

   string
       .chars()
       .rev()
       .enumerate()
       .fold(Some(0), |acc, (pos, c)| {
           parse_hex_digit(c).and_then(|n| acc.map(|acc| acc + n * base.pow(pos as u32)))
       })
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-88" id="填充相关-88"><h2>填充/相关</h2></a>
<a class="header" href="#nucleotide-codons" id="nucleotide-codons"><h1>nucleotide-codons</h1></a>
<a class="header" href="#1-readme-89" id="1-readme-89"><h2>1. Readme</h2></a>
<a class="header" href="#核苷酸密码子" id="核苷酸密码子"><h1>核苷酸密码子</h1></a>
<p>编写一个函数，返回一个特定密码子的氨基酸名称，可能使用速记，编码.</p>
<p>在 DNA 序列中，3 个核苷酸称为密码子，编码氨基酸。通常密码子编码相同的氨基酸。国际纯和应用化学联盟开发了一个简写系统，用于命名密码子组，其编码为相同氨基酸。</p>
<p>简单地说，他们把四个字母 A、C、G 和 T 扩展成一堆代表不同可能性的字母。例如 R 代表 A 和 G，
所以 TAR 可表示为 TAA 和 TAG (把 “TAR” 当成正则式形式的 “TA[AG]”)。</p>
<p>编写一些代码，给出一个密码子，可以使用速记，然后返回密码子所编码的氨基酸的名称。您将得到一个非速记密码/名称对的列表，可作为您计算的基础。</p>
<p>见:<a href="https://en.wikipedia.org/wiki/DNA_codon_table">维基百科</a>.</p>
<a class="header" href="#2-开始你的表演-89" id="2-开始你的表演-89"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">

</code></pre></pre>
<a class="header" href="#3-测试代码查看-89" id="3-测试代码查看-89"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn test_methionine() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;ATG&quot;), Ok(&quot;methionine&quot;));
}

#[test]
//#[ignore]
fn test_cysteine_tgt() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;TGT&quot;), Ok(&quot;cysteine&quot;));
}

#[test]
//#[ignore]
fn test_cysteine_tgy() {
   // &quot;compressed&quot; name for TGT and TGC
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;TGT&quot;), info.name_for(&quot;TGY&quot;));
   assert_eq!(info.name_for(&quot;TGC&quot;), info.name_for(&quot;TGY&quot;));
}

#[test]
//#[ignore]
fn test_stop() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;TAA&quot;), Ok(&quot;stop codon&quot;));
}

#[test]
//#[ignore]
fn test_valine() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;GTN&quot;), Ok(&quot;valine&quot;));
}

#[test]
//#[ignore]
fn test_isoleucine() {
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;ATH&quot;), Ok(&quot;isoleucine&quot;));
}

#[test]
//#[ignore]
fn test_arginine_name() {
   // In arginine CGA can be &quot;compressed&quot; both as CGN and as MGR
   let info = parse(make_pairs());
   assert_eq!(info.name_for(&quot;CGA&quot;), Ok(&quot;arginine&quot;));
   assert_eq!(info.name_for(&quot;CGN&quot;), Ok(&quot;arginine&quot;));
   assert_eq!(info.name_for(&quot;MGR&quot;), Ok(&quot;arginine&quot;));
}

#[test]
//#[ignore]
fn empty_is_invalid() {
   let info = parse(make_pairs());
   assert!(info.name_for(&quot;&quot;).is_err());
}

#[test]
//#[ignore]
fn x_is_not_shorthand_so_is_invalid() {
   let info = parse(make_pairs());
   assert!(info.name_for(&quot;VWX&quot;).is_err());
}

#[test]
//#[ignore]
fn too_short_is_invalid() {
   let info = parse(make_pairs());
   assert!(info.name_for(&quot;AT&quot;).is_err());
}

#[test]
//#[ignore]
fn too_long_is_invalid() {
   let info = parse(make_pairs());
   assert!(info.name_for(&quot;ATTA&quot;).is_err());
}

// The input data constructor. Returns a list of codon, name pairs.
fn make_pairs() -&gt; Vec&lt;(&amp;'static str, &amp;'static str)&gt; {
   let grouped = vec![
       (&quot;isoleucine&quot;, vec![&quot;ATT&quot;, &quot;ATC&quot;, &quot;ATA&quot;]),
       (&quot;leucine&quot;, vec![&quot;CTT&quot;, &quot;CTC&quot;, &quot;CTA&quot;, &quot;CTG&quot;, &quot;TTA&quot;, &quot;TTG&quot;]),
       (&quot;valine&quot;, vec![&quot;GTT&quot;, &quot;GTC&quot;, &quot;GTA&quot;, &quot;GTG&quot;]),
       (&quot;phenylalanine&quot;, vec![&quot;TTT&quot;, &quot;TTC&quot;]),
       (&quot;methionine&quot;, vec![&quot;ATG&quot;]),
       (&quot;cysteine&quot;, vec![&quot;TGT&quot;, &quot;TGC&quot;]),
       (&quot;alanine&quot;, vec![&quot;GCT&quot;, &quot;GCC&quot;, &quot;GCA&quot;, &quot;GCG&quot;]),
       (&quot;glycine&quot;, vec![&quot;GGT&quot;, &quot;GGC&quot;, &quot;GGA&quot;, &quot;GGG&quot;]),
       (&quot;proline&quot;, vec![&quot;CCT&quot;, &quot;CCC&quot;, &quot;CCA&quot;, &quot;CCG&quot;]),
       (&quot;threonine&quot;, vec![&quot;ACT&quot;, &quot;ACC&quot;, &quot;ACA&quot;, &quot;ACG&quot;]),
       (&quot;serine&quot;, vec![&quot;TCT&quot;, &quot;TCC&quot;, &quot;TCA&quot;, &quot;TCG&quot;, &quot;AGT&quot;, &quot;AGC&quot;]),
       (&quot;tyrosine&quot;, vec![&quot;TAT&quot;, &quot;TAC&quot;]),
       (&quot;tryptophan&quot;, vec![&quot;TGG&quot;]),
       (&quot;glutamine&quot;, vec![&quot;CAA&quot;, &quot;CAG&quot;]),
       (&quot;asparagine&quot;, vec![&quot;AAT&quot;, &quot;AAC&quot;]),
       (&quot;histidine&quot;, vec![&quot;CAT&quot;, &quot;CAC&quot;]),
       (&quot;glutamic acid&quot;, vec![&quot;GAA&quot;, &quot;GAG&quot;]),
       (&quot;aspartic acid&quot;, vec![&quot;GAT&quot;, &quot;GAC&quot;]),
       (&quot;lysine&quot;, vec![&quot;AAA&quot;, &quot;AAG&quot;]),
       (&quot;arginine&quot;, vec![&quot;CGT&quot;, &quot;CGC&quot;, &quot;CGA&quot;, &quot;CGG&quot;, &quot;AGA&quot;, &quot;AGG&quot;]),
       (&quot;stop codon&quot;, vec![&quot;TAA&quot;, &quot;TAG&quot;, &quot;TGA&quot;]),
   ];
   let mut pairs = Vec::&lt;(&amp;'static str, &amp;'static str)&gt;::new();
   for (name, codons) in grouped.into_iter() {
       for codon in codons {
           pairs.push((codon, name));
       }
   }
   pairs.sort_by(|&amp;(_, a), &amp;(_, b)| a.cmp(b));
   return pairs;
}

#}</code></pre></pre>
<a class="header" href="#4-答案-89" id="4-答案-89"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::collections::HashMap;

pub struct CodonInfo&lt;'a&gt; {
   actual_codons: HashMap&lt;&amp;'a str, &amp;'a str&gt;,
}

pub fn parse&lt;'a&gt;(pairs: Vec&lt;(&amp;'a str, &amp;'a str)&gt;) -&gt; CodonInfo&lt;'a&gt; {
   CodonInfo {
       actual_codons: pairs.into_iter().collect(),
   }
}

impl&lt;'a&gt; CodonInfo&lt;'a&gt; {
   pub fn name_for(&amp;self, codon: &amp;str) -&gt; Result&lt;&amp;'a str, &amp;'static str&gt; {
       if codon.len() != 3 {
           return Err(&quot;invalid length&quot;);
       }

       let mut valid = true;
       let lookup: String = codon
           .chars()
           .map(|l| {
               // Get an example of a &quot;letter&quot; represented by the possibly encoded letter.
               // Since every codon represented by the compressed notation has to be of
               // the desired amino acid just picking one at random will do.
               match l {
                   'A' | 'W' | 'M' | 'R' | 'D' | 'H' | 'V' | 'N' =&gt; 'A',
                   'C' | 'S' | 'Y' | 'B' =&gt; 'C',
                   'G' | 'K' =&gt; 'G',
                   'T' =&gt; 'T',
                   _ =&gt; {
                       valid = false;
                       ' '
                   }
               }
           })
           .collect();
       if !valid {
           return Err(&quot;invalid char&quot;);
       }

       // If the input table is correct (which it is) every valid codon is in it
       // so unwrap() shouldn't panic.
       Ok(self.actual_codons.get(&amp;lookup.as_ref()).unwrap())
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-89" id="填充相关-89"><h2>填充/相关</h2></a>
<a class="header" href="#two-fer" id="two-fer"><h1>two-fer</h1></a>
<a class="header" href="#1-readme-90" id="1-readme-90"><h2>1. Readme</h2></a>
<a class="header" href="#two-fer-1" id="two-fer-1"><h1>Two Fer</h1></a>
<p><code>Two-fer</code>或<code>2-fer</code>是 two for one 的缩写。One for you and one for me。</p>
<pre><code class="language-text">&quot;One for X, one for me.&quot;
</code></pre>
<p>当 X 是一个名字或<code>you</code>。</p>
<p>如果给定名称是<code>Alice</code>，结果应该是<code>One for Alice, one for me.</code>。如果没有给出名称，结果应该是<code>One for you, one for me.</code>。</p>
<a class="header" href="#资源-66" id="资源-66"><h2>资源</h2></a>
<p><a href="https://en.wikipedia.org/wiki/Two-fer">https://en.wikipedia.org/wiki/Two-fer</a></p>
<a class="header" href="#2-开始你的表演-90" id="2-开始你的表演-90"><h2>2. 开始你的表演</h2></a>
<pre><pre class="playpen"><code class="language-rust editable">pub fn twofer(name: &amp;str) -&gt; String {
   unimplemented!(&quot;One for {}, one for me.&quot;, name);
}

</code></pre></pre>
<a class="header" href="#3-测试代码查看-90" id="3-测试代码查看-90"><h2>3. 测试代码查看</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[test]
fn empty_string() {
   assert_eq!(twofer(&quot;&quot;), &quot;One for you, one for me.&quot;);
}

#[test]
//#[ignore]
fn alice() {
   assert_eq!(twofer(&quot;Alice&quot;), &quot;One for Alice, one for me.&quot;);
}

#[test]
//#[ignore]
fn bob() {
   assert_eq!(twofer(&quot;Bob&quot;), &quot;One for Bob, one for me.&quot;);
}

#}</code></pre></pre>
<a class="header" href="#4-答案-90" id="4-答案-90"><h2>4. 答案</h2></a>
<p><details></p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub fn twofer(name: &amp;str) -&gt; String {
   match name {
       &quot;&quot; =&gt; &quot;One for you, one for me.&quot;.to_string(),
       _ =&gt; format!(&quot;One for {}, one for me.&quot;, name),
   }
}

#}</code></pre></pre>
<p></details></p>
<hr />
<hr />
<a class="header" href="#填充相关-90" id="填充相关-90"><h2>填充/相关</h2></a>
<a class="header" href="#改为使用cargo-test" id="改为使用cargo-test"><h2>改为使用Cargo test</h2></a>
<p>正如万千生成工具，总是具有<code>主题/css样式/模版</code>之类的概念</p>
<p><a href="https://github.com/rust-lang-nursery/mdBook">mdBook</a> 也不例外</p>
<p>我们为了，让这份练习可在网页上运行并知道结果，借用了mdBook工具，它本身就具有<code>Rust Code</code>html元素运行的功能</p>
<p>可惜，也就相当于<code>Cargo run</code>,而我们要使用的是<code>Cargo test</code>。下面进入到我们的修改之旅</p>
<a class="header" href="#目录" id="目录"><h2>目录</h2></a>
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<ul>
<li><a href="#%E5%9F%BA%E7%A1%80%E7%BB%99%E7%AC%AC%E4%B8%80%E6%AC%A1%E4%BD%BF%E7%94%A8%E8%80%85">基础，给第一次使用者</a></li>
<li><a href="#%E5%85%A5%E4%B8%BB%E9%A2%98%E4%BD%BF%E7%94%A8%E8%BF%87mdbook">入主题，使用过mdBook</a>
<ul>
<li><a href="#bookjs">book.js</a>
<ul>
<li><a href="#%E4%BD%BF%E7%94%A8rust%E6%B8%B8%E4%B9%90%E5%9C%BA%E7%9A%84cargo-test">使用Rust游乐场的Cargo test</a></li>
<li><a href="#%E5%90%88%E5%B9%B6%E7%94%A8%E6%88%B7%E7%AD%94%E6%A1%88%E4%BB%A3%E7%A0%81%E4%B8%8E%E6%B5%8B%E8%AF%95%E4%BB%A3%E7%A0%81">合并(用户/答案代码)与测试代码</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#%E8%87%B3%E6%AD%A4%E5%AE%8C%E6%88%90%E8%B0%A2%E8%B0%A2%E6%B5%8F%E8%A7%88">至此，完成。谢谢浏览！</a>
<ul>
<li><a href="#%E7%9B%B8%E5%85%B3">相关</a></li>
</ul>
</li>
</ul>
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
<a class="header" href="#基础给第一次使用者" id="基础给第一次使用者"><h2>基础，给第一次使用者</h2></a>
<blockquote>
<p>安装就不讲了</p>
</blockquote>
<ul>
<li>初始化mdBook项目是这样的</li>
</ul>
<pre><code class="language-bash">mdBook init --theme
</code></pre>
<ul>
<li>它的主题之类，放在<code>src/theme</code>,结构是这样的</li>
</ul>
<pre><code class="language-bash">- theme
    - book.js # 默认的js改造
    - favicon.png
    - highlight.css
    - highlight.js
    - index.hbs # 默认的模版，引擎是hbs
    - css
        - chrome.css
        - general.css
        - print.css
        - variables.css
</code></pre>
<p>主要的，代码修改，落在了<code>book.js</code>中，它本身就是给<code>rust代码 元素</code>，(重点是)加上可与<a href="https://play.rust-lang.org/">rust游乐场</a>联系和运行代码，并返回结果的 <strong>播放按钮</strong>。</p>
<a class="header" href="#入主题使用过mdbook" id="入主题使用过mdbook"><h2>入主题，使用过mdBook</h2></a>
<a class="header" href="#bookjs" id="bookjs"><h3>book.js</h3></a>
<blockquote>
<p>这个代码文件本身有600多行，着重在使用<code>Cargo test</code>的部分</p>
</blockquote>
<a class="header" href="#使用rust游乐场的cargo-test" id="使用rust游乐场的cargo-test"><h4>使用Rust游乐场的Cargo test</h4></a>
<ul>
<li>原代码</li>
</ul>
<pre><code class="language-js">// ...
        var params = {
            version: &quot;stable&quot;,
            optimize: &quot;0&quot;,
            code: text
        };

        if (text.indexOf(&quot;#![feature&quot;) !== -1) {
            params.version = &quot;nightly&quot;;
        }

        result_block.innerText = &quot;Running...&quot;;
        // TODO cargo test
        fetch_with_timeout(&quot;https://play.rust-lang.org/evaluate.json&quot;, {
            headers: {
                'Content-Type': &quot;application/json&quot;,
            },
            method: 'POST',
            mode: 'cors',
            body: JSON.stringify(params)
        })
</code></pre>
<ul>
<li>
<p>修改</p>
</li>
</ul>
<ol>
<li>修改 POST的网址</li>
<li>修改 POST的body</li>
</ol>
<pre><code class="language-js">        var params = {
//           version: &quot;stable&quot;,
//           optimize: &quot;0&quot;,
            code: text,
            channel: &quot;stable&quot;,
            &quot;mode&quot;:&quot;debug&quot;,
            &quot;backtrace&quot;:false,
            tests: true,
            crateType: &quot;lib&quot;
        };

        if (text.indexOf(&quot;#![feature&quot;) !== -1) {
            params.version = &quot;nightly&quot;;
        }

        result_block.innerText = &quot;Running...&quot;;
        // TODO cargo test
//       fetch_with_timeout(&quot;https://play.rust-lang.org/evaluate.json&quot;, {
        fetch_with_timeout(&quot;https://play.rust-lang.org/execute&quot;, {
            headers: {
                'Content-Type': &quot;application/json&quot;,
            },
            
            method: 'POST',
            mode: 'cors',
            body: JSON.stringify(params)
        })
</code></pre>
<blockquote>
<p>这些是怎么知道，</p>
</blockquote>
<p>主要是通过游乐场，点击Test按钮后的调试器的流量检测。</p>
<a class="header" href="#合并用户答案代码与测试代码" id="合并用户答案代码与测试代码"><h4>合并(用户/答案代码)与测试代码</h4></a>
<ol>
<li>mdBook会为哪些没有写入<code>fn main//...</code>的Rust代码，写上类似下面<code>+</code>加号的代码</li>
</ol>
<pre><code class="language-md">+ #![allow(unused_variables)] 
+ fn main() {
#[test]
fn test_hello_world() {
    assert_eq!(&quot;Hello, World!&quot;, hello());
}

+ }
</code></pre>
<p>那好，我们就在<code>book.js</code>中，搞个去掉默认的函数</p>
<ul>
<li>全局函数:移除默认的<code>main</code></li>
</ul>
<pre><code class="language-js">function remove_default_main(text){
    var tArr = text.split(&quot;\n&quot;)
    if(tArr.slice(0,3).some(t =&gt;t.trim() == &quot;#![allow(unused_variables)]&quot;)){
        return tArr.slice(3,-1).join(&quot;\n&quot;)
    }
    return text

}
</code></pre>
<ol start="2">
<li>测试代码与其他(用户/答案代码),最大的不同就是<code>#[test]</code></li>
</ol>
<p>所有，我们为测试代码，找一个全局变量<code>document</code>下的安身之所</p>
<blockquote>
<p>为<code>document.mdBookTextCode</code>，book.js本身也为每个代码元素添加按钮，那正好用来检测哪个代码元素是测试代码</p>
</blockquote>
<pre><code class="language-js">    // Process playpen code blocks
    Array.from(document.querySelectorAll(&quot;.playpen&quot;)).forEach(function (pre_block) {
        // 添加测试代码，到全局变量document
        var codewithtest = playpen_text(pre_block)

        if(codewithtest.includes(&quot;#[test&quot;)){ // 测试代码，简单检验

            document.mdBookTextCode =  document.mdBookTextCode || remove_default_main(codewithtest)
        }
</code></pre>
<ol start="3">
<li>当点击运行代码的播放按钮，我们要适时加上测试代码</li>
</ol>
<blockquote>
<p>主要是(用户/答案代码)的播放按钮</p>
</blockquote>
<pre><code class="language-js">// 播放按钮的点击事件
    function run_rust_code(code_block) {
        var result_block = code_block.querySelector(&quot;.result&quot;);
        if (!result_block) {
            result_block = document.createElement('code');
            result_block.className = 'result hljs language-bash';

            code_block.append(result_block);
        }

        let text = playpen_text(code_block);
        // 如 不相等和 不包括测试代码，添加测试代码上去
        if(text != document.mdBookTextCode &amp;&amp; !text.includes(document.mdBookTextCode)){
            text = text + '\n' + document.mdBookTextCode
        }
// 说来也巧，我们的第一个修改也在这个点击事件，拼在一起看看
        var params = {
            code: text,
            channel: &quot;stable&quot;,
            &quot;mode&quot;:&quot;debug&quot;,
            &quot;backtrace&quot;:false,
            tests: true,
            crateType: &quot;lib&quot;
        };

        if (text.indexOf(&quot;#![feature&quot;) !== -1) {
            params.version = &quot;nightly&quot;;
        }

        result_block.innerText = &quot;Running...&quot;;
//       fetch_with_timeout(&quot;https://play.rust-lang.org/evaluate.json&quot;, {
        fetch_with_timeout(&quot;https://play.rust-lang.org/execute&quot;, {
            headers: {
                'Content-Type': &quot;application/json&quot;,
            },
            
            method: 'POST',
            mode: 'cors',
            body: JSON.stringify(params)
        })
</code></pre>
<a class="header" href="#至此完成谢谢浏览" id="至此完成谢谢浏览"><h2>至此，完成。谢谢浏览！</h2></a>
<a class="header" href="#相关" id="相关"><h3>相关</h3></a>
<p><a href="https://github.com/chinanf-boy/exercism-rust-zh/blob/master/theme/book.js">Github库/book.js</a></p>

                </main>

                <nav class="nav-wrapper" aria-label="Page navigation">
                    <!-- Mobile navigation buttons -->
                    

                    

                    <div style="clear: both"></div>
                </nav>
            </div>
        </div>

        <nav class="nav-wide-wrapper" aria-label="Page navigation">
            

            
        </nav>

    </div>

    

    
    <!-- Google Analytics Tag -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-128555056-1"></script>
    
    <script type="text/javascript">
        var localAddrs = ["localhost", "127.0.0.1", ""];
        if (localAddrs.indexOf(document.location.hostname) === -1) {
            window.dataLayer = window.dataLayer || [];
            function gtag() { dataLayer.push(arguments); }
            gtag('js', new Date());

            gtag('config', 'UA-128555056-1');
        }
    </script>
    

    
    <script src="ace.js" type="text/javascript" charset="utf-8"></script>
    <script src="editor.js" type="text/javascript" charset="utf-8"></script>
    <script src="mode-rust.js" type="text/javascript" charset="utf-8"></script>
    <script src="theme-dawn.js" type="text/javascript" charset="utf-8"></script>
    <script src="theme-tomorrow_night.js" type="text/javascript" charset="utf-8"></script>
    

    
    <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
    

    <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
    <script src="book.js" type="text/javascript" charset="utf-8"></script>

    <!-- Custom JS scripts -->
    

    
    
    <script type="text/javascript">
        window.addEventListener('load', function () {
            window.setTimeout(window.print, 100);
        });
    </script>
    
    

</body>

</html>